PackageManagerService.java revision 82b0842051a93764e96a68072da1a220f00c2c27
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_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
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.PARSE_IS_OEM;
86import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
87import static android.content.pm.PackageParser.isApkFile;
88import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
89import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
90import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
91import static android.system.OsConstants.O_CREAT;
92import static android.system.OsConstants.O_RDWR;
93
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
95import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
96import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
97import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
98import static com.android.internal.util.ArrayUtils.appendInt;
99import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
101import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
102import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
103import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
105import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
106import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
107import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
108import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
109import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageManagerInternal;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.Package;
167import android.content.pm.PackageParser.PackageLite;
168import android.content.pm.PackageParser.PackageParserException;
169import android.content.pm.PackageStats;
170import android.content.pm.PackageUserState;
171import android.content.pm.ParceledListSlice;
172import android.content.pm.PermissionGroupInfo;
173import android.content.pm.PermissionInfo;
174import android.content.pm.ProviderInfo;
175import android.content.pm.ResolveInfo;
176import android.content.pm.ServiceInfo;
177import android.content.pm.SharedLibraryInfo;
178import android.content.pm.Signature;
179import android.content.pm.UserInfo;
180import android.content.pm.VerifierDeviceIdentity;
181import android.content.pm.VerifierInfo;
182import android.content.pm.VersionedPackage;
183import android.content.res.Resources;
184import android.database.ContentObserver;
185import android.graphics.Bitmap;
186import android.hardware.display.DisplayManager;
187import android.net.Uri;
188import android.os.Binder;
189import android.os.Build;
190import android.os.Bundle;
191import android.os.Debug;
192import android.os.Environment;
193import android.os.Environment.UserEnvironment;
194import android.os.FileUtils;
195import android.os.Handler;
196import android.os.IBinder;
197import android.os.Looper;
198import android.os.Message;
199import android.os.Parcel;
200import android.os.ParcelFileDescriptor;
201import android.os.PatternMatcher;
202import android.os.Process;
203import android.os.RemoteCallbackList;
204import android.os.RemoteException;
205import android.os.ResultReceiver;
206import android.os.SELinux;
207import android.os.ServiceManager;
208import android.os.ShellCallback;
209import android.os.SystemClock;
210import android.os.SystemProperties;
211import android.os.Trace;
212import android.os.UserHandle;
213import android.os.UserManager;
214import android.os.UserManagerInternal;
215import android.os.storage.IStorageManager;
216import android.os.storage.StorageEventListener;
217import android.os.storage.StorageManager;
218import android.os.storage.StorageManagerInternal;
219import android.os.storage.VolumeInfo;
220import android.os.storage.VolumeRecord;
221import android.provider.Settings.Global;
222import android.provider.Settings.Secure;
223import android.security.KeyStore;
224import android.security.SystemKeyStore;
225import android.service.pm.PackageServiceDumpProto;
226import android.system.ErrnoException;
227import android.system.Os;
228import android.text.TextUtils;
229import android.text.format.DateUtils;
230import android.util.ArrayMap;
231import android.util.ArraySet;
232import android.util.Base64;
233import android.util.TimingsTraceLog;
234import android.util.DisplayMetrics;
235import android.util.EventLog;
236import android.util.ExceptionUtils;
237import android.util.Log;
238import android.util.LogPrinter;
239import android.util.MathUtils;
240import android.util.PackageUtils;
241import android.util.Pair;
242import android.util.PrintStreamPrinter;
243import android.util.Slog;
244import android.util.SparseArray;
245import android.util.SparseBooleanArray;
246import android.util.SparseIntArray;
247import android.util.Xml;
248import android.util.jar.StrictJarFile;
249import android.util.proto.ProtoOutputStream;
250import android.view.Display;
251
252import com.android.internal.R;
253import com.android.internal.annotations.GuardedBy;
254import com.android.internal.app.IMediaContainerService;
255import com.android.internal.app.ResolverActivity;
256import com.android.internal.content.NativeLibraryHelper;
257import com.android.internal.content.PackageHelper;
258import com.android.internal.logging.MetricsLogger;
259import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
260import com.android.internal.os.IParcelFileDescriptorFactory;
261import com.android.internal.os.RoSystemProperties;
262import com.android.internal.os.SomeArgs;
263import com.android.internal.os.Zygote;
264import com.android.internal.telephony.CarrierAppUtils;
265import com.android.internal.util.ArrayUtils;
266import com.android.internal.util.ConcurrentUtils;
267import com.android.internal.util.DumpUtils;
268import com.android.internal.util.FastPrintWriter;
269import com.android.internal.util.FastXmlSerializer;
270import com.android.internal.util.IndentingPrintWriter;
271import com.android.internal.util.Preconditions;
272import com.android.internal.util.XmlUtils;
273import com.android.server.AttributeCache;
274import com.android.server.DeviceIdleController;
275import com.android.server.EventLogTags;
276import com.android.server.FgThread;
277import com.android.server.IntentResolver;
278import com.android.server.LocalServices;
279import com.android.server.LockGuard;
280import com.android.server.ServiceThread;
281import com.android.server.SystemConfig;
282import com.android.server.SystemServerInitThreadPool;
283import com.android.server.Watchdog;
284import com.android.server.net.NetworkPolicyManagerInternal;
285import com.android.server.pm.Installer.InstallerException;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexManager;
289import com.android.server.pm.dex.DexoptOptions;
290import com.android.server.pm.dex.PackageDexUsage;
291import com.android.server.pm.permission.BasePermission;
292import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
293import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
294import com.android.server.pm.permission.PermissionsState;
295import com.android.server.pm.permission.PermissionsState.PermissionState;
296import com.android.server.storage.DeviceStorageMonitorInternal;
297
298import dalvik.system.CloseGuard;
299import dalvik.system.DexFile;
300import dalvik.system.VMRuntime;
301
302import libcore.io.IoUtils;
303import libcore.io.Streams;
304import libcore.util.EmptyArray;
305
306import org.xmlpull.v1.XmlPullParser;
307import org.xmlpull.v1.XmlPullParserException;
308import org.xmlpull.v1.XmlSerializer;
309
310import java.io.BufferedOutputStream;
311import java.io.BufferedReader;
312import java.io.ByteArrayInputStream;
313import java.io.ByteArrayOutputStream;
314import java.io.File;
315import java.io.FileDescriptor;
316import java.io.FileInputStream;
317import java.io.FileOutputStream;
318import java.io.FileReader;
319import java.io.FilenameFilter;
320import java.io.IOException;
321import java.io.InputStream;
322import java.io.OutputStream;
323import java.io.PrintWriter;
324import java.lang.annotation.Retention;
325import java.lang.annotation.RetentionPolicy;
326import java.nio.charset.StandardCharsets;
327import java.security.DigestInputStream;
328import java.security.MessageDigest;
329import java.security.NoSuchAlgorithmException;
330import java.security.PublicKey;
331import java.security.SecureRandom;
332import java.security.cert.Certificate;
333import java.security.cert.CertificateEncodingException;
334import java.security.cert.CertificateException;
335import java.text.SimpleDateFormat;
336import java.util.ArrayList;
337import java.util.Arrays;
338import java.util.Collection;
339import java.util.Collections;
340import java.util.Comparator;
341import java.util.Date;
342import java.util.HashMap;
343import java.util.HashSet;
344import java.util.Iterator;
345import java.util.List;
346import java.util.Map;
347import java.util.Objects;
348import java.util.Set;
349import java.util.concurrent.CountDownLatch;
350import java.util.concurrent.Future;
351import java.util.concurrent.TimeUnit;
352import java.util.concurrent.atomic.AtomicBoolean;
353import java.util.concurrent.atomic.AtomicInteger;
354import java.util.zip.GZIPInputStream;
355
356/**
357 * Keep track of all those APKs everywhere.
358 * <p>
359 * Internally there are two important locks:
360 * <ul>
361 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
362 * and other related state. It is a fine-grained lock that should only be held
363 * momentarily, as it's one of the most contended locks in the system.
364 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
365 * operations typically involve heavy lifting of application data on disk. Since
366 * {@code installd} is single-threaded, and it's operations can often be slow,
367 * this lock should never be acquired while already holding {@link #mPackages}.
368 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
369 * holding {@link #mInstallLock}.
370 * </ul>
371 * Many internal methods rely on the caller to hold the appropriate locks, and
372 * this contract is expressed through method name suffixes:
373 * <ul>
374 * <li>fooLI(): the caller must hold {@link #mInstallLock}
375 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
376 * being modified must be frozen
377 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
378 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
379 * </ul>
380 * <p>
381 * Because this class is very central to the platform's security; please run all
382 * CTS and unit tests whenever making modifications:
383 *
384 * <pre>
385 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
386 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
387 * </pre>
388 */
389public class PackageManagerService extends IPackageManager.Stub
390        implements PackageSender {
391    static final String TAG = "PackageManager";
392    public static final boolean DEBUG_SETTINGS = false;
393    static final boolean DEBUG_PREFERRED = false;
394    static final boolean DEBUG_UPGRADE = false;
395    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
396    private static final boolean DEBUG_BACKUP = false;
397    private static final boolean DEBUG_INSTALL = false;
398    private static final boolean DEBUG_REMOVE = false;
399    private static final boolean DEBUG_BROADCASTS = false;
400    private static final boolean DEBUG_SHOW_INFO = false;
401    private static final boolean DEBUG_PACKAGE_INFO = false;
402    private static final boolean DEBUG_INTENT_MATCHING = false;
403    public static final boolean DEBUG_PACKAGE_SCANNING = false;
404    private static final boolean DEBUG_VERIFY = false;
405    private static final boolean DEBUG_FILTERS = false;
406    private static final boolean DEBUG_PERMISSIONS = false;
407    private static final boolean DEBUG_SHARED_LIBRARIES = false;
408    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
409
410    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
411    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
412    // user, but by default initialize to this.
413    public static final boolean DEBUG_DEXOPT = false;
414
415    private static final boolean DEBUG_ABI_SELECTION = false;
416    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
417    private static final boolean DEBUG_TRIAGED_MISSING = false;
418    private static final boolean DEBUG_APP_DATA = false;
419
420    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
421    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
422
423    private static final boolean HIDE_EPHEMERAL_APIS = false;
424
425    private static final boolean ENABLE_FREE_CACHE_V2 =
426            SystemProperties.getBoolean("fw.free_cache_v2", true);
427
428    private static final int RADIO_UID = Process.PHONE_UID;
429    private static final int LOG_UID = Process.LOG_UID;
430    private static final int NFC_UID = Process.NFC_UID;
431    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
432    private static final int SHELL_UID = Process.SHELL_UID;
433
434    // Cap the size of permission trees that 3rd party apps can define
435    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
436
437    // Suffix used during package installation when copying/moving
438    // package apks to install directory.
439    private static final String INSTALL_PACKAGE_SUFFIX = "-";
440
441    static final int SCAN_NO_DEX = 1<<1;
442    static final int SCAN_FORCE_DEX = 1<<2;
443    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
444    static final int SCAN_NEW_INSTALL = 1<<4;
445    static final int SCAN_UPDATE_TIME = 1<<5;
446    static final int SCAN_BOOTING = 1<<6;
447    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
448    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
449    static final int SCAN_REPLACING = 1<<9;
450    static final int SCAN_REQUIRE_KNOWN = 1<<10;
451    static final int SCAN_MOVE = 1<<11;
452    static final int SCAN_INITIAL = 1<<12;
453    static final int SCAN_CHECK_ONLY = 1<<13;
454    static final int SCAN_DONT_KILL_APP = 1<<14;
455    static final int SCAN_IGNORE_FROZEN = 1<<15;
456    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
457    static final int SCAN_AS_INSTANT_APP = 1<<17;
458    static final int SCAN_AS_FULL_APP = 1<<18;
459    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
460    /** Should not be with the scan flags */
461    static final int FLAGS_REMOVE_CHATTY = 1<<31;
462
463    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
464    /** Extension of the compressed packages */
465    private final static String COMPRESSED_EXTENSION = ".gz";
466    /** Suffix of stub packages on the system partition */
467    private final static String STUB_SUFFIX = "-Stub";
468
469    private static final int[] EMPTY_INT_ARRAY = new int[0];
470
471    private static final int TYPE_UNKNOWN = 0;
472    private static final int TYPE_ACTIVITY = 1;
473    private static final int TYPE_RECEIVER = 2;
474    private static final int TYPE_SERVICE = 3;
475    private static final int TYPE_PROVIDER = 4;
476    @IntDef(prefix = { "TYPE_" }, value = {
477            TYPE_UNKNOWN,
478            TYPE_ACTIVITY,
479            TYPE_RECEIVER,
480            TYPE_SERVICE,
481            TYPE_PROVIDER,
482    })
483    @Retention(RetentionPolicy.SOURCE)
484    public @interface ComponentType {}
485
486    /**
487     * Timeout (in milliseconds) after which the watchdog should declare that
488     * our handler thread is wedged.  The usual default for such things is one
489     * minute but we sometimes do very lengthy I/O operations on this thread,
490     * such as installing multi-gigabyte applications, so ours needs to be longer.
491     */
492    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
493
494    /**
495     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
496     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
497     * settings entry if available, otherwise we use the hardcoded default.  If it's been
498     * more than this long since the last fstrim, we force one during the boot sequence.
499     *
500     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
501     * one gets run at the next available charging+idle time.  This final mandatory
502     * no-fstrim check kicks in only of the other scheduling criteria is never met.
503     */
504    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
505
506    /**
507     * Whether verification is enabled by default.
508     */
509    private static final boolean DEFAULT_VERIFY_ENABLE = true;
510
511    /**
512     * The default maximum time to wait for the verification agent to return in
513     * milliseconds.
514     */
515    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
516
517    /**
518     * The default response for package verification timeout.
519     *
520     * This can be either PackageManager.VERIFICATION_ALLOW or
521     * PackageManager.VERIFICATION_REJECT.
522     */
523    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
524
525    static final String PLATFORM_PACKAGE_NAME = "android";
526
527    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
528
529    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
530            DEFAULT_CONTAINER_PACKAGE,
531            "com.android.defcontainer.DefaultContainerService");
532
533    private static final String KILL_APP_REASON_GIDS_CHANGED =
534            "permission grant or revoke changed gids";
535
536    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
537            "permissions revoked";
538
539    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
540
541    private static final String PACKAGE_SCHEME = "package";
542
543    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
544
545    /** Permission grant: not grant the permission. */
546    private static final int GRANT_DENIED = 1;
547
548    /** Permission grant: grant the permission as an install permission. */
549    private static final int GRANT_INSTALL = 2;
550
551    /** Permission grant: grant the permission as a runtime one. */
552    private static final int GRANT_RUNTIME = 3;
553
554    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
555    private static final int GRANT_UPGRADE = 4;
556
557    /** Canonical intent used to identify what counts as a "web browser" app */
558    private static final Intent sBrowserIntent;
559    static {
560        sBrowserIntent = new Intent();
561        sBrowserIntent.setAction(Intent.ACTION_VIEW);
562        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
563        sBrowserIntent.setData(Uri.parse("http:"));
564    }
565
566    /**
567     * The set of all protected actions [i.e. those actions for which a high priority
568     * intent filter is disallowed].
569     */
570    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
571    static {
572        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
573        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
574        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
575        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
576    }
577
578    // Compilation reasons.
579    public static final int REASON_FIRST_BOOT = 0;
580    public static final int REASON_BOOT = 1;
581    public static final int REASON_INSTALL = 2;
582    public static final int REASON_BACKGROUND_DEXOPT = 3;
583    public static final int REASON_AB_OTA = 4;
584    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
585    public static final int REASON_SHARED = 6;
586
587    public static final int REASON_LAST = REASON_SHARED;
588
589    /** All dangerous permission names in the same order as the events in MetricsEvent */
590    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
591            Manifest.permission.READ_CALENDAR,
592            Manifest.permission.WRITE_CALENDAR,
593            Manifest.permission.CAMERA,
594            Manifest.permission.READ_CONTACTS,
595            Manifest.permission.WRITE_CONTACTS,
596            Manifest.permission.GET_ACCOUNTS,
597            Manifest.permission.ACCESS_FINE_LOCATION,
598            Manifest.permission.ACCESS_COARSE_LOCATION,
599            Manifest.permission.RECORD_AUDIO,
600            Manifest.permission.READ_PHONE_STATE,
601            Manifest.permission.CALL_PHONE,
602            Manifest.permission.READ_CALL_LOG,
603            Manifest.permission.WRITE_CALL_LOG,
604            Manifest.permission.ADD_VOICEMAIL,
605            Manifest.permission.USE_SIP,
606            Manifest.permission.PROCESS_OUTGOING_CALLS,
607            Manifest.permission.READ_CELL_BROADCASTS,
608            Manifest.permission.BODY_SENSORS,
609            Manifest.permission.SEND_SMS,
610            Manifest.permission.RECEIVE_SMS,
611            Manifest.permission.READ_SMS,
612            Manifest.permission.RECEIVE_WAP_PUSH,
613            Manifest.permission.RECEIVE_MMS,
614            Manifest.permission.READ_EXTERNAL_STORAGE,
615            Manifest.permission.WRITE_EXTERNAL_STORAGE,
616            Manifest.permission.READ_PHONE_NUMBERS,
617            Manifest.permission.ANSWER_PHONE_CALLS);
618
619
620    /**
621     * Version number for the package parser cache. Increment this whenever the format or
622     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
623     */
624    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
625
626    /**
627     * Whether the package parser cache is enabled.
628     */
629    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
630
631    final ServiceThread mHandlerThread;
632
633    final PackageHandler mHandler;
634
635    private final ProcessLoggingHandler mProcessLoggingHandler;
636
637    /**
638     * Messages for {@link #mHandler} that need to wait for system ready before
639     * being dispatched.
640     */
641    private ArrayList<Message> mPostSystemReadyMessages;
642
643    final int mSdkVersion = Build.VERSION.SDK_INT;
644
645    final Context mContext;
646    final boolean mFactoryTest;
647    final boolean mOnlyCore;
648    final DisplayMetrics mMetrics;
649    final int mDefParseFlags;
650    final String[] mSeparateProcesses;
651    final boolean mIsUpgrade;
652    final boolean mIsPreNUpgrade;
653    final boolean mIsPreNMR1Upgrade;
654
655    // Have we told the Activity Manager to whitelist the default container service by uid yet?
656    @GuardedBy("mPackages")
657    boolean mDefaultContainerWhitelisted = false;
658
659    @GuardedBy("mPackages")
660    private boolean mDexOptDialogShown;
661
662    /** The location for ASEC container files on internal storage. */
663    final String mAsecInternalPath;
664
665    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
666    // LOCK HELD.  Can be called with mInstallLock held.
667    @GuardedBy("mInstallLock")
668    final Installer mInstaller;
669
670    /** Directory where installed third-party apps stored */
671    final File mAppInstallDir;
672
673    /**
674     * Directory to which applications installed internally have their
675     * 32 bit native libraries copied.
676     */
677    private File mAppLib32InstallDir;
678
679    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
680    // apps.
681    final File mDrmAppPrivateInstallDir;
682
683    // ----------------------------------------------------------------
684
685    // Lock for state used when installing and doing other long running
686    // operations.  Methods that must be called with this lock held have
687    // the suffix "LI".
688    final Object mInstallLock = new Object();
689
690    // ----------------------------------------------------------------
691
692    // Keys are String (package name), values are Package.  This also serves
693    // as the lock for the global state.  Methods that must be called with
694    // this lock held have the prefix "LP".
695    @GuardedBy("mPackages")
696    final ArrayMap<String, PackageParser.Package> mPackages =
697            new ArrayMap<String, PackageParser.Package>();
698
699    final ArrayMap<String, Set<String>> mKnownCodebase =
700            new ArrayMap<String, Set<String>>();
701
702    // Keys are isolated uids and values are the uid of the application
703    // that created the isolated proccess.
704    @GuardedBy("mPackages")
705    final SparseIntArray mIsolatedOwners = new SparseIntArray();
706
707    /**
708     * Tracks new system packages [received in an OTA] that we expect to
709     * find updated user-installed versions. Keys are package name, values
710     * are package location.
711     */
712    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
713    /**
714     * Tracks high priority intent filters for protected actions. During boot, certain
715     * filter actions are protected and should never be allowed to have a high priority
716     * intent filter for them. However, there is one, and only one exception -- the
717     * setup wizard. It must be able to define a high priority intent filter for these
718     * actions to ensure there are no escapes from the wizard. We need to delay processing
719     * of these during boot as we need to look at all of the system packages in order
720     * to know which component is the setup wizard.
721     */
722    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
723    /**
724     * Whether or not processing protected filters should be deferred.
725     */
726    private boolean mDeferProtectedFilters = true;
727
728    /**
729     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
730     */
731    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
732    /**
733     * Whether or not system app permissions should be promoted from install to runtime.
734     */
735    boolean mPromoteSystemApps;
736
737    @GuardedBy("mPackages")
738    final Settings mSettings;
739
740    /**
741     * Set of package names that are currently "frozen", which means active
742     * surgery is being done on the code/data for that package. The platform
743     * will refuse to launch frozen packages to avoid race conditions.
744     *
745     * @see PackageFreezer
746     */
747    @GuardedBy("mPackages")
748    final ArraySet<String> mFrozenPackages = new ArraySet<>();
749
750    final ProtectedPackages mProtectedPackages;
751
752    @GuardedBy("mLoadedVolumes")
753    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
754
755    boolean mFirstBoot;
756
757    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
758
759    // System configuration read by SystemConfig.
760    final int[] mGlobalGids;
761    final SparseArray<ArraySet<String>> mSystemPermissions;
762    @GuardedBy("mAvailableFeatures")
763    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
764
765    // If mac_permissions.xml was found for seinfo labeling.
766    boolean mFoundPolicyFile;
767
768    private final InstantAppRegistry mInstantAppRegistry;
769
770    @GuardedBy("mPackages")
771    int mChangedPackagesSequenceNumber;
772    /**
773     * List of changed [installed, removed or updated] packages.
774     * mapping from user id -> sequence number -> package name
775     */
776    @GuardedBy("mPackages")
777    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
778    /**
779     * The sequence number of the last change to a package.
780     * mapping from user id -> package name -> sequence number
781     */
782    @GuardedBy("mPackages")
783    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
784
785    class PackageParserCallback implements PackageParser.Callback {
786        @Override public final boolean hasFeature(String feature) {
787            return PackageManagerService.this.hasSystemFeature(feature, 0);
788        }
789
790        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
791                Collection<PackageParser.Package> allPackages, String targetPackageName) {
792            List<PackageParser.Package> overlayPackages = null;
793            for (PackageParser.Package p : allPackages) {
794                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
795                    if (overlayPackages == null) {
796                        overlayPackages = new ArrayList<PackageParser.Package>();
797                    }
798                    overlayPackages.add(p);
799                }
800            }
801            if (overlayPackages != null) {
802                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
803                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
804                        return p1.mOverlayPriority - p2.mOverlayPriority;
805                    }
806                };
807                Collections.sort(overlayPackages, cmp);
808            }
809            return overlayPackages;
810        }
811
812        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
813                String targetPackageName, String targetPath) {
814            if ("android".equals(targetPackageName)) {
815                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
816                // native AssetManager.
817                return null;
818            }
819            List<PackageParser.Package> overlayPackages =
820                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
821            if (overlayPackages == null || overlayPackages.isEmpty()) {
822                return null;
823            }
824            List<String> overlayPathList = null;
825            for (PackageParser.Package overlayPackage : overlayPackages) {
826                if (targetPath == null) {
827                    if (overlayPathList == null) {
828                        overlayPathList = new ArrayList<String>();
829                    }
830                    overlayPathList.add(overlayPackage.baseCodePath);
831                    continue;
832                }
833
834                try {
835                    // Creates idmaps for system to parse correctly the Android manifest of the
836                    // target package.
837                    //
838                    // OverlayManagerService will update each of them with a correct gid from its
839                    // target package app id.
840                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
841                            UserHandle.getSharedAppGid(
842                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
843                    if (overlayPathList == null) {
844                        overlayPathList = new ArrayList<String>();
845                    }
846                    overlayPathList.add(overlayPackage.baseCodePath);
847                } catch (InstallerException e) {
848                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
849                            overlayPackage.baseCodePath);
850                }
851            }
852            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
853        }
854
855        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
856            synchronized (mPackages) {
857                return getStaticOverlayPathsLocked(
858                        mPackages.values(), targetPackageName, targetPath);
859            }
860        }
861
862        @Override public final String[] getOverlayApks(String targetPackageName) {
863            return getStaticOverlayPaths(targetPackageName, null);
864        }
865
866        @Override public final String[] getOverlayPaths(String targetPackageName,
867                String targetPath) {
868            return getStaticOverlayPaths(targetPackageName, targetPath);
869        }
870    }
871
872    class ParallelPackageParserCallback extends PackageParserCallback {
873        List<PackageParser.Package> mOverlayPackages = null;
874
875        void findStaticOverlayPackages() {
876            synchronized (mPackages) {
877                for (PackageParser.Package p : mPackages.values()) {
878                    if (p.mIsStaticOverlay) {
879                        if (mOverlayPackages == null) {
880                            mOverlayPackages = new ArrayList<PackageParser.Package>();
881                        }
882                        mOverlayPackages.add(p);
883                    }
884                }
885            }
886        }
887
888        @Override
889        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
890            // We can trust mOverlayPackages without holding mPackages because package uninstall
891            // can't happen while running parallel parsing.
892            // Moreover holding mPackages on each parsing thread causes dead-lock.
893            return mOverlayPackages == null ? null :
894                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
895        }
896    }
897
898    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
899    final ParallelPackageParserCallback mParallelPackageParserCallback =
900            new ParallelPackageParserCallback();
901
902    public static final class SharedLibraryEntry {
903        public final @Nullable String path;
904        public final @Nullable String apk;
905        public final @NonNull SharedLibraryInfo info;
906
907        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
908                String declaringPackageName, int declaringPackageVersionCode) {
909            path = _path;
910            apk = _apk;
911            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
912                    declaringPackageName, declaringPackageVersionCode), null);
913        }
914    }
915
916    // Currently known shared libraries.
917    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
918    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
919            new ArrayMap<>();
920
921    // All available activities, for your resolving pleasure.
922    final ActivityIntentResolver mActivities =
923            new ActivityIntentResolver();
924
925    // All available receivers, for your resolving pleasure.
926    final ActivityIntentResolver mReceivers =
927            new ActivityIntentResolver();
928
929    // All available services, for your resolving pleasure.
930    final ServiceIntentResolver mServices = new ServiceIntentResolver();
931
932    // All available providers, for your resolving pleasure.
933    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
934
935    // Mapping from provider base names (first directory in content URI codePath)
936    // to the provider information.
937    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
938            new ArrayMap<String, PackageParser.Provider>();
939
940    // Mapping from instrumentation class names to info about them.
941    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
942            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
943
944    // Mapping from permission names to info about them.
945    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
946            new ArrayMap<String, PackageParser.PermissionGroup>();
947
948    // Packages whose data we have transfered into another package, thus
949    // should no longer exist.
950    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
951
952    // Broadcast actions that are only available to the system.
953    @GuardedBy("mProtectedBroadcasts")
954    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
955
956    /** List of packages waiting for verification. */
957    final SparseArray<PackageVerificationState> mPendingVerification
958            = new SparseArray<PackageVerificationState>();
959
960    /** Set of packages associated with each app op permission. */
961    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
962
963    final PackageInstallerService mInstallerService;
964
965    private final PackageDexOptimizer mPackageDexOptimizer;
966    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
967    // is used by other apps).
968    private final DexManager mDexManager;
969
970    private AtomicInteger mNextMoveId = new AtomicInteger();
971    private final MoveCallbacks mMoveCallbacks;
972
973    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
974
975    // Cache of users who need badging.
976    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
977
978    /** Token for keys in mPendingVerification. */
979    private int mPendingVerificationToken = 0;
980
981    volatile boolean mSystemReady;
982    volatile boolean mSafeMode;
983    volatile boolean mHasSystemUidErrors;
984    private volatile boolean mEphemeralAppsDisabled;
985
986    ApplicationInfo mAndroidApplication;
987    final ActivityInfo mResolveActivity = new ActivityInfo();
988    final ResolveInfo mResolveInfo = new ResolveInfo();
989    ComponentName mResolveComponentName;
990    PackageParser.Package mPlatformPackage;
991    ComponentName mCustomResolverComponentName;
992
993    boolean mResolverReplaced = false;
994
995    private final @Nullable ComponentName mIntentFilterVerifierComponent;
996    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
997
998    private int mIntentFilterVerificationToken = 0;
999
1000    /** The service connection to the ephemeral resolver */
1001    final EphemeralResolverConnection mInstantAppResolverConnection;
1002    /** Component used to show resolver settings for Instant Apps */
1003    final ComponentName mInstantAppResolverSettingsComponent;
1004
1005    /** Activity used to install instant applications */
1006    ActivityInfo mInstantAppInstallerActivity;
1007    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1008
1009    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1010            = new SparseArray<IntentFilterVerificationState>();
1011
1012    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1013
1014    // List of packages names to keep cached, even if they are uninstalled for all users
1015    private List<String> mKeepUninstalledPackages;
1016
1017    private UserManagerInternal mUserManagerInternal;
1018
1019    private DeviceIdleController.LocalService mDeviceIdleController;
1020
1021    private File mCacheDir;
1022
1023    private ArraySet<String> mPrivappPermissionsViolations;
1024
1025    private Future<?> mPrepareAppDataFuture;
1026
1027    private static class IFVerificationParams {
1028        PackageParser.Package pkg;
1029        boolean replacing;
1030        int userId;
1031        int verifierUid;
1032
1033        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1034                int _userId, int _verifierUid) {
1035            pkg = _pkg;
1036            replacing = _replacing;
1037            userId = _userId;
1038            replacing = _replacing;
1039            verifierUid = _verifierUid;
1040        }
1041    }
1042
1043    private interface IntentFilterVerifier<T extends IntentFilter> {
1044        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1045                                               T filter, String packageName);
1046        void startVerifications(int userId);
1047        void receiveVerificationResponse(int verificationId);
1048    }
1049
1050    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1051        private Context mContext;
1052        private ComponentName mIntentFilterVerifierComponent;
1053        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1054
1055        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1056            mContext = context;
1057            mIntentFilterVerifierComponent = verifierComponent;
1058        }
1059
1060        private String getDefaultScheme() {
1061            return IntentFilter.SCHEME_HTTPS;
1062        }
1063
1064        @Override
1065        public void startVerifications(int userId) {
1066            // Launch verifications requests
1067            int count = mCurrentIntentFilterVerifications.size();
1068            for (int n=0; n<count; n++) {
1069                int verificationId = mCurrentIntentFilterVerifications.get(n);
1070                final IntentFilterVerificationState ivs =
1071                        mIntentFilterVerificationStates.get(verificationId);
1072
1073                String packageName = ivs.getPackageName();
1074
1075                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1076                final int filterCount = filters.size();
1077                ArraySet<String> domainsSet = new ArraySet<>();
1078                for (int m=0; m<filterCount; m++) {
1079                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1080                    domainsSet.addAll(filter.getHostsList());
1081                }
1082                synchronized (mPackages) {
1083                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1084                            packageName, domainsSet) != null) {
1085                        scheduleWriteSettingsLocked();
1086                    }
1087                }
1088                sendVerificationRequest(verificationId, ivs);
1089            }
1090            mCurrentIntentFilterVerifications.clear();
1091        }
1092
1093        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1094            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1097                    verificationId);
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1100                    getDefaultScheme());
1101            verificationIntent.putExtra(
1102                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1103                    ivs.getHostsString());
1104            verificationIntent.putExtra(
1105                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1106                    ivs.getPackageName());
1107            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1108            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1109
1110            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1111            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1112                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1113                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1114
1115            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1116            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1117                    "Sending IntentFilter verification broadcast");
1118        }
1119
1120        public void receiveVerificationResponse(int verificationId) {
1121            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1122
1123            final boolean verified = ivs.isVerified();
1124
1125            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1126            final int count = filters.size();
1127            if (DEBUG_DOMAIN_VERIFICATION) {
1128                Slog.i(TAG, "Received verification response " + verificationId
1129                        + " for " + count + " filters, verified=" + verified);
1130            }
1131            for (int n=0; n<count; n++) {
1132                PackageParser.ActivityIntentInfo filter = filters.get(n);
1133                filter.setVerified(verified);
1134
1135                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1136                        + " verified with result:" + verified + " and hosts:"
1137                        + ivs.getHostsString());
1138            }
1139
1140            mIntentFilterVerificationStates.remove(verificationId);
1141
1142            final String packageName = ivs.getPackageName();
1143            IntentFilterVerificationInfo ivi = null;
1144
1145            synchronized (mPackages) {
1146                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1147            }
1148            if (ivi == null) {
1149                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1150                        + verificationId + " packageName:" + packageName);
1151                return;
1152            }
1153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1154                    "Updating IntentFilterVerificationInfo for package " + packageName
1155                            +" verificationId:" + verificationId);
1156
1157            synchronized (mPackages) {
1158                if (verified) {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1160                } else {
1161                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1162                }
1163                scheduleWriteSettingsLocked();
1164
1165                final int userId = ivs.getUserId();
1166                if (userId != UserHandle.USER_ALL) {
1167                    final int userStatus =
1168                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1169
1170                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1171                    boolean needUpdate = false;
1172
1173                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1174                    // already been set by the User thru the Disambiguation dialog
1175                    switch (userStatus) {
1176                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1177                            if (verified) {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1179                            } else {
1180                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1181                            }
1182                            needUpdate = true;
1183                            break;
1184
1185                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1186                            if (verified) {
1187                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1188                                needUpdate = true;
1189                            }
1190                            break;
1191
1192                        default:
1193                            // Nothing to do
1194                    }
1195
1196                    if (needUpdate) {
1197                        mSettings.updateIntentFilterVerificationStatusLPw(
1198                                packageName, updatedStatus, userId);
1199                        scheduleWritePackageRestrictionsLocked(userId);
1200                    }
1201                }
1202            }
1203        }
1204
1205        @Override
1206        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1207                    ActivityIntentInfo filter, String packageName) {
1208            if (!hasValidDomains(filter)) {
1209                return false;
1210            }
1211            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1212            if (ivs == null) {
1213                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1214                        packageName);
1215            }
1216            if (DEBUG_DOMAIN_VERIFICATION) {
1217                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1218            }
1219            ivs.addFilter(filter);
1220            return true;
1221        }
1222
1223        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1224                int userId, int verificationId, String packageName) {
1225            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1226                    verifierUid, userId, packageName);
1227            ivs.setPendingState();
1228            synchronized (mPackages) {
1229                mIntentFilterVerificationStates.append(verificationId, ivs);
1230                mCurrentIntentFilterVerifications.add(verificationId);
1231            }
1232            return ivs;
1233        }
1234    }
1235
1236    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1237        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1238                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1239                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1240    }
1241
1242    // Set of pending broadcasts for aggregating enable/disable of components.
1243    static class PendingPackageBroadcasts {
1244        // for each user id, a map of <package name -> components within that package>
1245        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1246
1247        public PendingPackageBroadcasts() {
1248            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1249        }
1250
1251        public ArrayList<String> get(int userId, String packageName) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            return packages.get(packageName);
1254        }
1255
1256        public void put(int userId, String packageName, ArrayList<String> components) {
1257            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1258            packages.put(packageName, components);
1259        }
1260
1261        public void remove(int userId, String packageName) {
1262            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1263            if (packages != null) {
1264                packages.remove(packageName);
1265            }
1266        }
1267
1268        public void remove(int userId) {
1269            mUidMap.remove(userId);
1270        }
1271
1272        public int userIdCount() {
1273            return mUidMap.size();
1274        }
1275
1276        public int userIdAt(int n) {
1277            return mUidMap.keyAt(n);
1278        }
1279
1280        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1281            return mUidMap.get(userId);
1282        }
1283
1284        public int size() {
1285            // total number of pending broadcast entries across all userIds
1286            int num = 0;
1287            for (int i = 0; i< mUidMap.size(); i++) {
1288                num += mUidMap.valueAt(i).size();
1289            }
1290            return num;
1291        }
1292
1293        public void clear() {
1294            mUidMap.clear();
1295        }
1296
1297        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1298            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1299            if (map == null) {
1300                map = new ArrayMap<String, ArrayList<String>>();
1301                mUidMap.put(userId, map);
1302            }
1303            return map;
1304        }
1305    }
1306    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1307
1308    // Service Connection to remote media container service to copy
1309    // package uri's from external media onto secure containers
1310    // or internal storage.
1311    private IMediaContainerService mContainerService = null;
1312
1313    static final int SEND_PENDING_BROADCAST = 1;
1314    static final int MCS_BOUND = 3;
1315    static final int END_COPY = 4;
1316    static final int INIT_COPY = 5;
1317    static final int MCS_UNBIND = 6;
1318    static final int START_CLEANING_PACKAGE = 7;
1319    static final int FIND_INSTALL_LOC = 8;
1320    static final int POST_INSTALL = 9;
1321    static final int MCS_RECONNECT = 10;
1322    static final int MCS_GIVE_UP = 11;
1323    static final int UPDATED_MEDIA_STATUS = 12;
1324    static final int WRITE_SETTINGS = 13;
1325    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1326    static final int PACKAGE_VERIFIED = 15;
1327    static final int CHECK_PENDING_VERIFICATION = 16;
1328    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1329    static final int INTENT_FILTER_VERIFIED = 18;
1330    static final int WRITE_PACKAGE_LIST = 19;
1331    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1332
1333    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1334
1335    // Delay time in millisecs
1336    static final int BROADCAST_DELAY = 10 * 1000;
1337
1338    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1339            2 * 60 * 60 * 1000L; /* two hours */
1340
1341    static UserManagerService sUserManager;
1342
1343    // Stores a list of users whose package restrictions file needs to be updated
1344    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1345
1346    final private DefaultContainerConnection mDefContainerConn =
1347            new DefaultContainerConnection();
1348    class DefaultContainerConnection implements ServiceConnection {
1349        public void onServiceConnected(ComponentName name, IBinder service) {
1350            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1351            final IMediaContainerService imcs = IMediaContainerService.Stub
1352                    .asInterface(Binder.allowBlocking(service));
1353            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1354        }
1355
1356        public void onServiceDisconnected(ComponentName name) {
1357            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1358        }
1359    }
1360
1361    // Recordkeeping of restore-after-install operations that are currently in flight
1362    // between the Package Manager and the Backup Manager
1363    static class PostInstallData {
1364        public InstallArgs args;
1365        public PackageInstalledInfo res;
1366
1367        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1368            args = _a;
1369            res = _r;
1370        }
1371    }
1372
1373    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1374    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1375
1376    // XML tags for backup/restore of various bits of state
1377    private static final String TAG_PREFERRED_BACKUP = "pa";
1378    private static final String TAG_DEFAULT_APPS = "da";
1379    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1380
1381    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1382    private static final String TAG_ALL_GRANTS = "rt-grants";
1383    private static final String TAG_GRANT = "grant";
1384    private static final String ATTR_PACKAGE_NAME = "pkg";
1385
1386    private static final String TAG_PERMISSION = "perm";
1387    private static final String ATTR_PERMISSION_NAME = "name";
1388    private static final String ATTR_IS_GRANTED = "g";
1389    private static final String ATTR_USER_SET = "set";
1390    private static final String ATTR_USER_FIXED = "fixed";
1391    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1392
1393    // System/policy permission grants are not backed up
1394    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_POLICY_FIXED
1396            | FLAG_PERMISSION_SYSTEM_FIXED
1397            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1398
1399    // And we back up these user-adjusted states
1400    private static final int USER_RUNTIME_GRANT_MASK =
1401            FLAG_PERMISSION_USER_SET
1402            | FLAG_PERMISSION_USER_FIXED
1403            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1404
1405    final @Nullable String mRequiredVerifierPackage;
1406    final @NonNull String mRequiredInstallerPackage;
1407    final @NonNull String mRequiredUninstallerPackage;
1408    final @Nullable String mSetupWizardPackage;
1409    final @Nullable String mStorageManagerPackage;
1410    final @NonNull String mServicesSystemSharedLibraryPackageName;
1411    final @NonNull String mSharedSystemSharedLibraryPackageName;
1412
1413    final boolean mPermissionReviewRequired;
1414
1415    private final PackageUsage mPackageUsage = new PackageUsage();
1416    private final CompilerStats mCompilerStats = new CompilerStats();
1417
1418    class PackageHandler extends Handler {
1419        private boolean mBound = false;
1420        final ArrayList<HandlerParams> mPendingInstalls =
1421            new ArrayList<HandlerParams>();
1422
1423        private boolean connectToService() {
1424            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1425                    " DefaultContainerService");
1426            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1427            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1428            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1429                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1430                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1431                mBound = true;
1432                return true;
1433            }
1434            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1435            return false;
1436        }
1437
1438        private void disconnectService() {
1439            mContainerService = null;
1440            mBound = false;
1441            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1442            mContext.unbindService(mDefContainerConn);
1443            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1444        }
1445
1446        PackageHandler(Looper looper) {
1447            super(looper);
1448        }
1449
1450        public void handleMessage(Message msg) {
1451            try {
1452                doHandleMessage(msg);
1453            } finally {
1454                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1455            }
1456        }
1457
1458        void doHandleMessage(Message msg) {
1459            switch (msg.what) {
1460                case INIT_COPY: {
1461                    HandlerParams params = (HandlerParams) msg.obj;
1462                    int idx = mPendingInstalls.size();
1463                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1464                    // If a bind was already initiated we dont really
1465                    // need to do anything. The pending install
1466                    // will be processed later on.
1467                    if (!mBound) {
1468                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1469                                System.identityHashCode(mHandler));
1470                        // If this is the only one pending we might
1471                        // have to bind to the service again.
1472                        if (!connectToService()) {
1473                            Slog.e(TAG, "Failed to bind to media container service");
1474                            params.serviceError();
1475                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1476                                    System.identityHashCode(mHandler));
1477                            if (params.traceMethod != null) {
1478                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1479                                        params.traceCookie);
1480                            }
1481                            return;
1482                        } else {
1483                            // Once we bind to the service, the first
1484                            // pending request will be processed.
1485                            mPendingInstalls.add(idx, params);
1486                        }
1487                    } else {
1488                        mPendingInstalls.add(idx, params);
1489                        // Already bound to the service. Just make
1490                        // sure we trigger off processing the first request.
1491                        if (idx == 0) {
1492                            mHandler.sendEmptyMessage(MCS_BOUND);
1493                        }
1494                    }
1495                    break;
1496                }
1497                case MCS_BOUND: {
1498                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1499                    if (msg.obj != null) {
1500                        mContainerService = (IMediaContainerService) msg.obj;
1501                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1502                                System.identityHashCode(mHandler));
1503                    }
1504                    if (mContainerService == null) {
1505                        if (!mBound) {
1506                            // Something seriously wrong since we are not bound and we are not
1507                            // waiting for connection. Bail out.
1508                            Slog.e(TAG, "Cannot bind to media container service");
1509                            for (HandlerParams params : mPendingInstalls) {
1510                                // Indicate service bind error
1511                                params.serviceError();
1512                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1513                                        System.identityHashCode(params));
1514                                if (params.traceMethod != null) {
1515                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1516                                            params.traceMethod, params.traceCookie);
1517                                }
1518                                return;
1519                            }
1520                            mPendingInstalls.clear();
1521                        } else {
1522                            Slog.w(TAG, "Waiting to connect to media container service");
1523                        }
1524                    } else if (mPendingInstalls.size() > 0) {
1525                        HandlerParams params = mPendingInstalls.get(0);
1526                        if (params != null) {
1527                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1528                                    System.identityHashCode(params));
1529                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1530                            if (params.startCopy()) {
1531                                // We are done...  look for more work or to
1532                                // go idle.
1533                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1534                                        "Checking for more work or unbind...");
1535                                // Delete pending install
1536                                if (mPendingInstalls.size() > 0) {
1537                                    mPendingInstalls.remove(0);
1538                                }
1539                                if (mPendingInstalls.size() == 0) {
1540                                    if (mBound) {
1541                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                                "Posting delayed MCS_UNBIND");
1543                                        removeMessages(MCS_UNBIND);
1544                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1545                                        // Unbind after a little delay, to avoid
1546                                        // continual thrashing.
1547                                        sendMessageDelayed(ubmsg, 10000);
1548                                    }
1549                                } else {
1550                                    // There are more pending requests in queue.
1551                                    // Just post MCS_BOUND message to trigger processing
1552                                    // of next pending install.
1553                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1554                                            "Posting MCS_BOUND for next work");
1555                                    mHandler.sendEmptyMessage(MCS_BOUND);
1556                                }
1557                            }
1558                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1559                        }
1560                    } else {
1561                        // Should never happen ideally.
1562                        Slog.w(TAG, "Empty queue");
1563                    }
1564                    break;
1565                }
1566                case MCS_RECONNECT: {
1567                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1568                    if (mPendingInstalls.size() > 0) {
1569                        if (mBound) {
1570                            disconnectService();
1571                        }
1572                        if (!connectToService()) {
1573                            Slog.e(TAG, "Failed to bind to media container service");
1574                            for (HandlerParams params : mPendingInstalls) {
1575                                // Indicate service bind error
1576                                params.serviceError();
1577                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1578                                        System.identityHashCode(params));
1579                            }
1580                            mPendingInstalls.clear();
1581                        }
1582                    }
1583                    break;
1584                }
1585                case MCS_UNBIND: {
1586                    // If there is no actual work left, then time to unbind.
1587                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1588
1589                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1590                        if (mBound) {
1591                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1592
1593                            disconnectService();
1594                        }
1595                    } else if (mPendingInstalls.size() > 0) {
1596                        // There are more pending requests in queue.
1597                        // Just post MCS_BOUND message to trigger processing
1598                        // of next pending install.
1599                        mHandler.sendEmptyMessage(MCS_BOUND);
1600                    }
1601
1602                    break;
1603                }
1604                case MCS_GIVE_UP: {
1605                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1606                    HandlerParams params = mPendingInstalls.remove(0);
1607                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1608                            System.identityHashCode(params));
1609                    break;
1610                }
1611                case SEND_PENDING_BROADCAST: {
1612                    String packages[];
1613                    ArrayList<String> components[];
1614                    int size = 0;
1615                    int uids[];
1616                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1617                    synchronized (mPackages) {
1618                        if (mPendingBroadcasts == null) {
1619                            return;
1620                        }
1621                        size = mPendingBroadcasts.size();
1622                        if (size <= 0) {
1623                            // Nothing to be done. Just return
1624                            return;
1625                        }
1626                        packages = new String[size];
1627                        components = new ArrayList[size];
1628                        uids = new int[size];
1629                        int i = 0;  // filling out the above arrays
1630
1631                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1632                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1633                            Iterator<Map.Entry<String, ArrayList<String>>> it
1634                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1635                                            .entrySet().iterator();
1636                            while (it.hasNext() && i < size) {
1637                                Map.Entry<String, ArrayList<String>> ent = it.next();
1638                                packages[i] = ent.getKey();
1639                                components[i] = ent.getValue();
1640                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1641                                uids[i] = (ps != null)
1642                                        ? UserHandle.getUid(packageUserId, ps.appId)
1643                                        : -1;
1644                                i++;
1645                            }
1646                        }
1647                        size = i;
1648                        mPendingBroadcasts.clear();
1649                    }
1650                    // Send broadcasts
1651                    for (int i = 0; i < size; i++) {
1652                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1653                    }
1654                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1655                    break;
1656                }
1657                case START_CLEANING_PACKAGE: {
1658                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1659                    final String packageName = (String)msg.obj;
1660                    final int userId = msg.arg1;
1661                    final boolean andCode = msg.arg2 != 0;
1662                    synchronized (mPackages) {
1663                        if (userId == UserHandle.USER_ALL) {
1664                            int[] users = sUserManager.getUserIds();
1665                            for (int user : users) {
1666                                mSettings.addPackageToCleanLPw(
1667                                        new PackageCleanItem(user, packageName, andCode));
1668                            }
1669                        } else {
1670                            mSettings.addPackageToCleanLPw(
1671                                    new PackageCleanItem(userId, packageName, andCode));
1672                        }
1673                    }
1674                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1675                    startCleaningPackages();
1676                } break;
1677                case POST_INSTALL: {
1678                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1679
1680                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1681                    final boolean didRestore = (msg.arg2 != 0);
1682                    mRunningInstalls.delete(msg.arg1);
1683
1684                    if (data != null) {
1685                        InstallArgs args = data.args;
1686                        PackageInstalledInfo parentRes = data.res;
1687
1688                        final boolean grantPermissions = (args.installFlags
1689                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1690                        final boolean killApp = (args.installFlags
1691                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1692                        final boolean virtualPreload = ((args.installFlags
1693                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1694                        final String[] grantedPermissions = args.installGrantPermissions;
1695
1696                        // Handle the parent package
1697                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1698                                virtualPreload, grantedPermissions, didRestore,
1699                                args.installerPackageName, args.observer);
1700
1701                        // Handle the child packages
1702                        final int childCount = (parentRes.addedChildPackages != null)
1703                                ? parentRes.addedChildPackages.size() : 0;
1704                        for (int i = 0; i < childCount; i++) {
1705                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1706                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1707                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1708                                    args.installerPackageName, args.observer);
1709                        }
1710
1711                        // Log tracing if needed
1712                        if (args.traceMethod != null) {
1713                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1714                                    args.traceCookie);
1715                        }
1716                    } else {
1717                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1718                    }
1719
1720                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1721                } break;
1722                case UPDATED_MEDIA_STATUS: {
1723                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1724                    boolean reportStatus = msg.arg1 == 1;
1725                    boolean doGc = msg.arg2 == 1;
1726                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1727                    if (doGc) {
1728                        // Force a gc to clear up stale containers.
1729                        Runtime.getRuntime().gc();
1730                    }
1731                    if (msg.obj != null) {
1732                        @SuppressWarnings("unchecked")
1733                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1734                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1735                        // Unload containers
1736                        unloadAllContainers(args);
1737                    }
1738                    if (reportStatus) {
1739                        try {
1740                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1741                                    "Invoking StorageManagerService call back");
1742                            PackageHelper.getStorageManager().finishMediaUpdate();
1743                        } catch (RemoteException e) {
1744                            Log.e(TAG, "StorageManagerService not running?");
1745                        }
1746                    }
1747                } break;
1748                case WRITE_SETTINGS: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_SETTINGS);
1752                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1753                        mSettings.writeLPr();
1754                        mDirtyUsers.clear();
1755                    }
1756                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1757                } break;
1758                case WRITE_PACKAGE_RESTRICTIONS: {
1759                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1760                    synchronized (mPackages) {
1761                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1762                        for (int userId : mDirtyUsers) {
1763                            mSettings.writePackageRestrictionsLPr(userId);
1764                        }
1765                        mDirtyUsers.clear();
1766                    }
1767                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1768                } break;
1769                case WRITE_PACKAGE_LIST: {
1770                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1771                    synchronized (mPackages) {
1772                        removeMessages(WRITE_PACKAGE_LIST);
1773                        mSettings.writePackageListLPr(msg.arg1);
1774                    }
1775                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1776                } break;
1777                case CHECK_PENDING_VERIFICATION: {
1778                    final int verificationId = msg.arg1;
1779                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1780
1781                    if ((state != null) && !state.timeoutExtended()) {
1782                        final InstallArgs args = state.getInstallArgs();
1783                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1784
1785                        Slog.i(TAG, "Verification timed out for " + originUri);
1786                        mPendingVerification.remove(verificationId);
1787
1788                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1789
1790                        final UserHandle user = args.getUser();
1791                        if (getDefaultVerificationResponse(user)
1792                                == PackageManager.VERIFICATION_ALLOW) {
1793                            Slog.i(TAG, "Continuing with installation of " + originUri);
1794                            state.setVerifierResponse(Binder.getCallingUid(),
1795                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1796                            broadcastPackageVerified(verificationId, originUri,
1797                                    PackageManager.VERIFICATION_ALLOW, user);
1798                            try {
1799                                ret = args.copyApk(mContainerService, true);
1800                            } catch (RemoteException e) {
1801                                Slog.e(TAG, "Could not contact the ContainerService");
1802                            }
1803                        } else {
1804                            broadcastPackageVerified(verificationId, originUri,
1805                                    PackageManager.VERIFICATION_REJECT, user);
1806                        }
1807
1808                        Trace.asyncTraceEnd(
1809                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1810
1811                        processPendingInstall(args, ret);
1812                        mHandler.sendEmptyMessage(MCS_UNBIND);
1813                    }
1814                    break;
1815                }
1816                case PACKAGE_VERIFIED: {
1817                    final int verificationId = msg.arg1;
1818
1819                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1820                    if (state == null) {
1821                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1822                        break;
1823                    }
1824
1825                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1826
1827                    state.setVerifierResponse(response.callerUid, response.code);
1828
1829                    if (state.isVerificationComplete()) {
1830                        mPendingVerification.remove(verificationId);
1831
1832                        final InstallArgs args = state.getInstallArgs();
1833                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1834
1835                        int ret;
1836                        if (state.isInstallAllowed()) {
1837                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1838                            broadcastPackageVerified(verificationId, originUri,
1839                                    response.code, state.getInstallArgs().getUser());
1840                            try {
1841                                ret = args.copyApk(mContainerService, true);
1842                            } catch (RemoteException e) {
1843                                Slog.e(TAG, "Could not contact the ContainerService");
1844                            }
1845                        } else {
1846                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1847                        }
1848
1849                        Trace.asyncTraceEnd(
1850                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1851
1852                        processPendingInstall(args, ret);
1853                        mHandler.sendEmptyMessage(MCS_UNBIND);
1854                    }
1855
1856                    break;
1857                }
1858                case START_INTENT_FILTER_VERIFICATIONS: {
1859                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1860                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1861                            params.replacing, params.pkg);
1862                    break;
1863                }
1864                case INTENT_FILTER_VERIFIED: {
1865                    final int verificationId = msg.arg1;
1866
1867                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1868                            verificationId);
1869                    if (state == null) {
1870                        Slog.w(TAG, "Invalid IntentFilter verification token "
1871                                + verificationId + " received");
1872                        break;
1873                    }
1874
1875                    final int userId = state.getUserId();
1876
1877                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1878                            "Processing IntentFilter verification with token:"
1879                            + verificationId + " and userId:" + userId);
1880
1881                    final IntentFilterVerificationResponse response =
1882                            (IntentFilterVerificationResponse) msg.obj;
1883
1884                    state.setVerifierResponse(response.callerUid, response.code);
1885
1886                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1887                            "IntentFilter verification with token:" + verificationId
1888                            + " and userId:" + userId
1889                            + " is settings verifier response with response code:"
1890                            + response.code);
1891
1892                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1893                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1894                                + response.getFailedDomainsString());
1895                    }
1896
1897                    if (state.isVerificationComplete()) {
1898                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1899                    } else {
1900                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1901                                "IntentFilter verification with token:" + verificationId
1902                                + " was not said to be complete");
1903                    }
1904
1905                    break;
1906                }
1907                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1908                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1909                            mInstantAppResolverConnection,
1910                            (InstantAppRequest) msg.obj,
1911                            mInstantAppInstallerActivity,
1912                            mHandler);
1913                }
1914            }
1915        }
1916    }
1917
1918    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1919            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1920            boolean launchedForRestore, String installerPackage,
1921            IPackageInstallObserver2 installObserver) {
1922        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1923            // Send the removed broadcasts
1924            if (res.removedInfo != null) {
1925                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1926            }
1927
1928            // Now that we successfully installed the package, grant runtime
1929            // permissions if requested before broadcasting the install. Also
1930            // for legacy apps in permission review mode we clear the permission
1931            // review flag which is used to emulate runtime permissions for
1932            // legacy apps.
1933            if (grantPermissions) {
1934                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1935            }
1936
1937            final boolean update = res.removedInfo != null
1938                    && res.removedInfo.removedPackage != null;
1939            final String installerPackageName =
1940                    res.installerPackageName != null
1941                            ? res.installerPackageName
1942                            : res.removedInfo != null
1943                                    ? res.removedInfo.installerPackageName
1944                                    : null;
1945
1946            // If this is the first time we have child packages for a disabled privileged
1947            // app that had no children, we grant requested runtime permissions to the new
1948            // children if the parent on the system image had them already granted.
1949            if (res.pkg.parentPackage != null) {
1950                synchronized (mPackages) {
1951                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1952                }
1953            }
1954
1955            synchronized (mPackages) {
1956                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1957            }
1958
1959            final String packageName = res.pkg.applicationInfo.packageName;
1960
1961            // Determine the set of users who are adding this package for
1962            // the first time vs. those who are seeing an update.
1963            int[] firstUsers = EMPTY_INT_ARRAY;
1964            int[] updateUsers = EMPTY_INT_ARRAY;
1965            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1966            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1967            for (int newUser : res.newUsers) {
1968                if (ps.getInstantApp(newUser)) {
1969                    continue;
1970                }
1971                if (allNewUsers) {
1972                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1973                    continue;
1974                }
1975                boolean isNew = true;
1976                for (int origUser : res.origUsers) {
1977                    if (origUser == newUser) {
1978                        isNew = false;
1979                        break;
1980                    }
1981                }
1982                if (isNew) {
1983                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1984                } else {
1985                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1986                }
1987            }
1988
1989            // Send installed broadcasts if the package is not a static shared lib.
1990            if (res.pkg.staticSharedLibName == null) {
1991                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1992
1993                // Send added for users that see the package for the first time
1994                // sendPackageAddedForNewUsers also deals with system apps
1995                int appId = UserHandle.getAppId(res.uid);
1996                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1997                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1998                        virtualPreload /*startReceiver*/, appId, firstUsers);
1999
2000                // Send added for users that don't see the package for the first time
2001                Bundle extras = new Bundle(1);
2002                extras.putInt(Intent.EXTRA_UID, res.uid);
2003                if (update) {
2004                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2005                }
2006                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2007                        extras, 0 /*flags*/,
2008                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2009                if (installerPackageName != null) {
2010                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2011                            extras, 0 /*flags*/,
2012                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2013                }
2014
2015                // Send replaced for users that don't see the package for the first time
2016                if (update) {
2017                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2018                            packageName, extras, 0 /*flags*/,
2019                            null /*targetPackage*/, null /*finishedReceiver*/,
2020                            updateUsers);
2021                    if (installerPackageName != null) {
2022                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2023                                extras, 0 /*flags*/,
2024                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2025                    }
2026                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2027                            null /*package*/, null /*extras*/, 0 /*flags*/,
2028                            packageName /*targetPackage*/,
2029                            null /*finishedReceiver*/, updateUsers);
2030                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2031                    // First-install and we did a restore, so we're responsible for the
2032                    // first-launch broadcast.
2033                    if (DEBUG_BACKUP) {
2034                        Slog.i(TAG, "Post-restore of " + packageName
2035                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2036                    }
2037                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2038                }
2039
2040                // Send broadcast package appeared if forward locked/external for all users
2041                // treat asec-hosted packages like removable media on upgrade
2042                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2043                    if (DEBUG_INSTALL) {
2044                        Slog.i(TAG, "upgrading pkg " + res.pkg
2045                                + " is ASEC-hosted -> AVAILABLE");
2046                    }
2047                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2048                    ArrayList<String> pkgList = new ArrayList<>(1);
2049                    pkgList.add(packageName);
2050                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2051                }
2052            }
2053
2054            // Work that needs to happen on first install within each user
2055            if (firstUsers != null && firstUsers.length > 0) {
2056                synchronized (mPackages) {
2057                    for (int userId : firstUsers) {
2058                        // If this app is a browser and it's newly-installed for some
2059                        // users, clear any default-browser state in those users. The
2060                        // app's nature doesn't depend on the user, so we can just check
2061                        // its browser nature in any user and generalize.
2062                        if (packageIsBrowser(packageName, userId)) {
2063                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2064                        }
2065
2066                        // We may also need to apply pending (restored) runtime
2067                        // permission grants within these users.
2068                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2069                    }
2070                }
2071            }
2072
2073            // Log current value of "unknown sources" setting
2074            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2075                    getUnknownSourcesSettings());
2076
2077            // Remove the replaced package's older resources safely now
2078            // We delete after a gc for applications  on sdcard.
2079            if (res.removedInfo != null && res.removedInfo.args != null) {
2080                Runtime.getRuntime().gc();
2081                synchronized (mInstallLock) {
2082                    res.removedInfo.args.doPostDeleteLI(true);
2083                }
2084            } else {
2085                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2086                // and not block here.
2087                VMRuntime.getRuntime().requestConcurrentGC();
2088            }
2089
2090            // Notify DexManager that the package was installed for new users.
2091            // The updated users should already be indexed and the package code paths
2092            // should not change.
2093            // Don't notify the manager for ephemeral apps as they are not expected to
2094            // survive long enough to benefit of background optimizations.
2095            for (int userId : firstUsers) {
2096                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2097                // There's a race currently where some install events may interleave with an uninstall.
2098                // This can lead to package info being null (b/36642664).
2099                if (info != null) {
2100                    mDexManager.notifyPackageInstalled(info, userId);
2101                }
2102            }
2103        }
2104
2105        // If someone is watching installs - notify them
2106        if (installObserver != null) {
2107            try {
2108                Bundle extras = extrasForInstallResult(res);
2109                installObserver.onPackageInstalled(res.name, res.returnCode,
2110                        res.returnMsg, extras);
2111            } catch (RemoteException e) {
2112                Slog.i(TAG, "Observer no longer exists.");
2113            }
2114        }
2115    }
2116
2117    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2118            PackageParser.Package pkg) {
2119        if (pkg.parentPackage == null) {
2120            return;
2121        }
2122        if (pkg.requestedPermissions == null) {
2123            return;
2124        }
2125        final PackageSetting disabledSysParentPs = mSettings
2126                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2127        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2128                || !disabledSysParentPs.isPrivileged()
2129                || (disabledSysParentPs.childPackageNames != null
2130                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2131            return;
2132        }
2133        final int[] allUserIds = sUserManager.getUserIds();
2134        final int permCount = pkg.requestedPermissions.size();
2135        for (int i = 0; i < permCount; i++) {
2136            String permission = pkg.requestedPermissions.get(i);
2137            BasePermission bp = mSettings.mPermissions.get(permission);
2138            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2139                continue;
2140            }
2141            for (int userId : allUserIds) {
2142                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2143                        permission, userId)) {
2144                    grantRuntimePermission(pkg.packageName, permission, userId);
2145                }
2146            }
2147        }
2148    }
2149
2150    private StorageEventListener mStorageListener = new StorageEventListener() {
2151        @Override
2152        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2153            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2154                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2155                    final String volumeUuid = vol.getFsUuid();
2156
2157                    // Clean up any users or apps that were removed or recreated
2158                    // while this volume was missing
2159                    sUserManager.reconcileUsers(volumeUuid);
2160                    reconcileApps(volumeUuid);
2161
2162                    // Clean up any install sessions that expired or were
2163                    // cancelled while this volume was missing
2164                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2165
2166                    loadPrivatePackages(vol);
2167
2168                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2169                    unloadPrivatePackages(vol);
2170                }
2171            }
2172
2173            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2174                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2175                    updateExternalMediaStatus(true, false);
2176                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2177                    updateExternalMediaStatus(false, false);
2178                }
2179            }
2180        }
2181
2182        @Override
2183        public void onVolumeForgotten(String fsUuid) {
2184            if (TextUtils.isEmpty(fsUuid)) {
2185                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2186                return;
2187            }
2188
2189            // Remove any apps installed on the forgotten volume
2190            synchronized (mPackages) {
2191                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2192                for (PackageSetting ps : packages) {
2193                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2194                    deletePackageVersioned(new VersionedPackage(ps.name,
2195                            PackageManager.VERSION_CODE_HIGHEST),
2196                            new LegacyPackageDeleteObserver(null).getBinder(),
2197                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2198                    // Try very hard to release any references to this package
2199                    // so we don't risk the system server being killed due to
2200                    // open FDs
2201                    AttributeCache.instance().removePackage(ps.name);
2202                }
2203
2204                mSettings.onVolumeForgotten(fsUuid);
2205                mSettings.writeLPr();
2206            }
2207        }
2208    };
2209
2210    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2211            String[] grantedPermissions) {
2212        for (int userId : userIds) {
2213            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2214        }
2215    }
2216
2217    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2218            String[] grantedPermissions) {
2219        PackageSetting ps = (PackageSetting) pkg.mExtras;
2220        if (ps == null) {
2221            return;
2222        }
2223
2224        PermissionsState permissionsState = ps.getPermissionsState();
2225
2226        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2227                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2228
2229        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2230                >= Build.VERSION_CODES.M;
2231
2232        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2233
2234        for (String permission : pkg.requestedPermissions) {
2235            final BasePermission bp;
2236            synchronized (mPackages) {
2237                bp = mSettings.mPermissions.get(permission);
2238            }
2239            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2240                    && (!instantApp || bp.isInstant())
2241                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2242                    && (grantedPermissions == null
2243                           || ArrayUtils.contains(grantedPermissions, permission))) {
2244                final int flags = permissionsState.getPermissionFlags(permission, userId);
2245                if (supportsRuntimePermissions) {
2246                    // Installer cannot change immutable permissions.
2247                    if ((flags & immutableFlags) == 0) {
2248                        grantRuntimePermission(pkg.packageName, permission, userId);
2249                    }
2250                } else if (mPermissionReviewRequired) {
2251                    // In permission review mode we clear the review flag when we
2252                    // are asked to install the app with all permissions granted.
2253                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2254                        updatePermissionFlags(permission, pkg.packageName,
2255                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2256                    }
2257                }
2258            }
2259        }
2260    }
2261
2262    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2263        Bundle extras = null;
2264        switch (res.returnCode) {
2265            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2266                extras = new Bundle();
2267                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2268                        res.origPermission);
2269                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2270                        res.origPackage);
2271                break;
2272            }
2273            case PackageManager.INSTALL_SUCCEEDED: {
2274                extras = new Bundle();
2275                extras.putBoolean(Intent.EXTRA_REPLACING,
2276                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2277                break;
2278            }
2279        }
2280        return extras;
2281    }
2282
2283    void scheduleWriteSettingsLocked() {
2284        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2285            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2286        }
2287    }
2288
2289    void scheduleWritePackageListLocked(int userId) {
2290        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2291            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2292            msg.arg1 = userId;
2293            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2294        }
2295    }
2296
2297    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2298        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2299        scheduleWritePackageRestrictionsLocked(userId);
2300    }
2301
2302    void scheduleWritePackageRestrictionsLocked(int userId) {
2303        final int[] userIds = (userId == UserHandle.USER_ALL)
2304                ? sUserManager.getUserIds() : new int[]{userId};
2305        for (int nextUserId : userIds) {
2306            if (!sUserManager.exists(nextUserId)) return;
2307            mDirtyUsers.add(nextUserId);
2308            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2309                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2310            }
2311        }
2312    }
2313
2314    public static PackageManagerService main(Context context, Installer installer,
2315            boolean factoryTest, boolean onlyCore) {
2316        // Self-check for initial settings.
2317        PackageManagerServiceCompilerMapping.checkProperties();
2318
2319        PackageManagerService m = new PackageManagerService(context, installer,
2320                factoryTest, onlyCore);
2321        m.enableSystemUserPackages();
2322        ServiceManager.addService("package", m);
2323        final PackageManagerNative pmn = m.new PackageManagerNative();
2324        ServiceManager.addService("package_native", pmn);
2325        return m;
2326    }
2327
2328    private void enableSystemUserPackages() {
2329        if (!UserManager.isSplitSystemUser()) {
2330            return;
2331        }
2332        // For system user, enable apps based on the following conditions:
2333        // - app is whitelisted or belong to one of these groups:
2334        //   -- system app which has no launcher icons
2335        //   -- system app which has INTERACT_ACROSS_USERS permission
2336        //   -- system IME app
2337        // - app is not in the blacklist
2338        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2339        Set<String> enableApps = new ArraySet<>();
2340        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2341                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2342                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2343        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2344        enableApps.addAll(wlApps);
2345        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2346                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2347        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2348        enableApps.removeAll(blApps);
2349        Log.i(TAG, "Applications installed for system user: " + enableApps);
2350        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2351                UserHandle.SYSTEM);
2352        final int allAppsSize = allAps.size();
2353        synchronized (mPackages) {
2354            for (int i = 0; i < allAppsSize; i++) {
2355                String pName = allAps.get(i);
2356                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2357                // Should not happen, but we shouldn't be failing if it does
2358                if (pkgSetting == null) {
2359                    continue;
2360                }
2361                boolean install = enableApps.contains(pName);
2362                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2363                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2364                            + " for system user");
2365                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2366                }
2367            }
2368            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2369        }
2370    }
2371
2372    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2373        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2374                Context.DISPLAY_SERVICE);
2375        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2376    }
2377
2378    /**
2379     * Requests that files preopted on a secondary system partition be copied to the data partition
2380     * if possible.  Note that the actual copying of the files is accomplished by init for security
2381     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2382     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2383     */
2384    private static void requestCopyPreoptedFiles() {
2385        final int WAIT_TIME_MS = 100;
2386        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2387        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2388            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2389            // We will wait for up to 100 seconds.
2390            final long timeStart = SystemClock.uptimeMillis();
2391            final long timeEnd = timeStart + 100 * 1000;
2392            long timeNow = timeStart;
2393            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2394                try {
2395                    Thread.sleep(WAIT_TIME_MS);
2396                } catch (InterruptedException e) {
2397                    // Do nothing
2398                }
2399                timeNow = SystemClock.uptimeMillis();
2400                if (timeNow > timeEnd) {
2401                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2402                    Slog.wtf(TAG, "cppreopt did not finish!");
2403                    break;
2404                }
2405            }
2406
2407            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2408        }
2409    }
2410
2411    public PackageManagerService(Context context, Installer installer,
2412            boolean factoryTest, boolean onlyCore) {
2413        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2414        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2415        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2416                SystemClock.uptimeMillis());
2417
2418        if (mSdkVersion <= 0) {
2419            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2420        }
2421
2422        mContext = context;
2423
2424        mPermissionReviewRequired = context.getResources().getBoolean(
2425                R.bool.config_permissionReviewRequired);
2426
2427        mFactoryTest = factoryTest;
2428        mOnlyCore = onlyCore;
2429        mMetrics = new DisplayMetrics();
2430        mSettings = new Settings(mPackages);
2431        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2440                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2441        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2442                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2443
2444        String separateProcesses = SystemProperties.get("debug.separate_processes");
2445        if (separateProcesses != null && separateProcesses.length() > 0) {
2446            if ("*".equals(separateProcesses)) {
2447                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2448                mSeparateProcesses = null;
2449                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2450            } else {
2451                mDefParseFlags = 0;
2452                mSeparateProcesses = separateProcesses.split(",");
2453                Slog.w(TAG, "Running with debug.separate_processes: "
2454                        + separateProcesses);
2455            }
2456        } else {
2457            mDefParseFlags = 0;
2458            mSeparateProcesses = null;
2459        }
2460
2461        mInstaller = installer;
2462        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2463                "*dexopt*");
2464        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2465        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2466
2467        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2468                FgThread.get().getLooper());
2469
2470        getDefaultDisplayMetrics(context, mMetrics);
2471
2472        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2473        SystemConfig systemConfig = SystemConfig.getInstance();
2474        mGlobalGids = systemConfig.getGlobalGids();
2475        mSystemPermissions = systemConfig.getSystemPermissions();
2476        mAvailableFeatures = systemConfig.getAvailableFeatures();
2477        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2478
2479        mProtectedPackages = new ProtectedPackages(mContext);
2480
2481        synchronized (mInstallLock) {
2482        // writer
2483        synchronized (mPackages) {
2484            // Expose private service for system components to use.
2485            LocalServices.addService(
2486                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2487
2488            mHandlerThread = new ServiceThread(TAG,
2489                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2490            mHandlerThread.start();
2491            mHandler = new PackageHandler(mHandlerThread.getLooper());
2492            mProcessLoggingHandler = new ProcessLoggingHandler();
2493            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2494            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(
2495                    mContext, mHandlerThread.getLooper(), new DefaultPermissionGrantedCallback() {
2496                        @Override
2497                        public void onDefaultRuntimePermissionsGranted(int userId) {
2498                            synchronized(mPackages) {
2499                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2500                            }
2501                        }
2502                    });
2503            mInstantAppRegistry = new InstantAppRegistry(this);
2504
2505            File dataDir = Environment.getDataDirectory();
2506            mAppInstallDir = new File(dataDir, "app");
2507            mAppLib32InstallDir = new File(dataDir, "app-lib");
2508            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2509            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2510            sUserManager = new UserManagerService(context, this,
2511                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2512
2513            // Propagate permission configuration in to package manager.
2514            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2515                    = systemConfig.getPermissions();
2516            for (int i=0; i<permConfig.size(); i++) {
2517                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2518                BasePermission bp = mSettings.mPermissions.get(perm.name);
2519                if (bp == null) {
2520                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2521                    mSettings.mPermissions.put(perm.name, bp);
2522                }
2523                if (perm.gids != null) {
2524                    bp.setGids(perm.gids, perm.perUser);
2525                }
2526            }
2527
2528            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2529            final int builtInLibCount = libConfig.size();
2530            for (int i = 0; i < builtInLibCount; i++) {
2531                String name = libConfig.keyAt(i);
2532                String path = libConfig.valueAt(i);
2533                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2534                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2535            }
2536
2537            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2538
2539            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2540            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2541            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2542
2543            // Clean up orphaned packages for which the code path doesn't exist
2544            // and they are an update to a system app - caused by bug/32321269
2545            final int packageSettingCount = mSettings.mPackages.size();
2546            for (int i = packageSettingCount - 1; i >= 0; i--) {
2547                PackageSetting ps = mSettings.mPackages.valueAt(i);
2548                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2549                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2550                    mSettings.mPackages.removeAt(i);
2551                    mSettings.enableSystemPackageLPw(ps.name);
2552                }
2553            }
2554
2555            if (mFirstBoot) {
2556                requestCopyPreoptedFiles();
2557            }
2558
2559            String customResolverActivity = Resources.getSystem().getString(
2560                    R.string.config_customResolverActivity);
2561            if (TextUtils.isEmpty(customResolverActivity)) {
2562                customResolverActivity = null;
2563            } else {
2564                mCustomResolverComponentName = ComponentName.unflattenFromString(
2565                        customResolverActivity);
2566            }
2567
2568            long startTime = SystemClock.uptimeMillis();
2569
2570            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2571                    startTime);
2572
2573            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2574            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2575
2576            if (bootClassPath == null) {
2577                Slog.w(TAG, "No BOOTCLASSPATH found!");
2578            }
2579
2580            if (systemServerClassPath == null) {
2581                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2582            }
2583
2584            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2585
2586            final VersionInfo ver = mSettings.getInternalVersion();
2587            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2588            if (mIsUpgrade) {
2589                logCriticalInfo(Log.INFO,
2590                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2591            }
2592
2593            // when upgrading from pre-M, promote system app permissions from install to runtime
2594            mPromoteSystemApps =
2595                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2596
2597            // When upgrading from pre-N, we need to handle package extraction like first boot,
2598            // as there is no profiling data available.
2599            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2600
2601            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2602
2603            // save off the names of pre-existing system packages prior to scanning; we don't
2604            // want to automatically grant runtime permissions for new system apps
2605            if (mPromoteSystemApps) {
2606                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2607                while (pkgSettingIter.hasNext()) {
2608                    PackageSetting ps = pkgSettingIter.next();
2609                    if (isSystemApp(ps)) {
2610                        mExistingSystemPackages.add(ps.name);
2611                    }
2612                }
2613            }
2614
2615            mCacheDir = preparePackageParserCache(mIsUpgrade);
2616
2617            // Set flag to monitor and not change apk file paths when
2618            // scanning install directories.
2619            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2620
2621            if (mIsUpgrade || mFirstBoot) {
2622                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2623            }
2624
2625            // Collect vendor overlay packages. (Do this before scanning any apps.)
2626            // For security and version matching reason, only consider
2627            // overlay packages if they reside in the right directory.
2628            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM
2630                    | PackageParser.PARSE_IS_SYSTEM_DIR
2631                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2632
2633            mParallelPackageParserCallback.findStaticOverlayPackages();
2634
2635            // Find base frameworks (resource packages without code).
2636            scanDirTracedLI(frameworkDir, mDefParseFlags
2637                    | PackageParser.PARSE_IS_SYSTEM
2638                    | PackageParser.PARSE_IS_SYSTEM_DIR
2639                    | PackageParser.PARSE_IS_PRIVILEGED,
2640                    scanFlags | SCAN_NO_DEX, 0);
2641
2642            // Collected privileged system packages.
2643            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2644            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2645                    | PackageParser.PARSE_IS_SYSTEM
2646                    | PackageParser.PARSE_IS_SYSTEM_DIR
2647                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2648
2649            // Collect ordinary system packages.
2650            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2651            scanDirTracedLI(systemAppDir, mDefParseFlags
2652                    | PackageParser.PARSE_IS_SYSTEM
2653                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2654
2655            // Collect all vendor packages.
2656            File vendorAppDir = new File("/vendor/app");
2657            try {
2658                vendorAppDir = vendorAppDir.getCanonicalFile();
2659            } catch (IOException e) {
2660                // failed to look up canonical path, continue with original one
2661            }
2662            scanDirTracedLI(vendorAppDir, mDefParseFlags
2663                    | PackageParser.PARSE_IS_SYSTEM
2664                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2665
2666            // Collect all OEM packages.
2667            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2668            scanDirTracedLI(oemAppDir, mDefParseFlags
2669                    | PackageParser.PARSE_IS_SYSTEM
2670                    | PackageParser.PARSE_IS_SYSTEM_DIR
2671                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2672
2673            // Prune any system packages that no longer exist.
2674            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2675            // Stub packages must either be replaced with full versions in the /data
2676            // partition or be disabled.
2677            final List<String> stubSystemApps = new ArrayList<>();
2678            if (!mOnlyCore) {
2679                // do this first before mucking with mPackages for the "expecting better" case
2680                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2681                while (pkgIterator.hasNext()) {
2682                    final PackageParser.Package pkg = pkgIterator.next();
2683                    if (pkg.isStub) {
2684                        stubSystemApps.add(pkg.packageName);
2685                    }
2686                }
2687
2688                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2689                while (psit.hasNext()) {
2690                    PackageSetting ps = psit.next();
2691
2692                    /*
2693                     * If this is not a system app, it can't be a
2694                     * disable system app.
2695                     */
2696                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2697                        continue;
2698                    }
2699
2700                    /*
2701                     * If the package is scanned, it's not erased.
2702                     */
2703                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2704                    if (scannedPkg != null) {
2705                        /*
2706                         * If the system app is both scanned and in the
2707                         * disabled packages list, then it must have been
2708                         * added via OTA. Remove it from the currently
2709                         * scanned package so the previously user-installed
2710                         * application can be scanned.
2711                         */
2712                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2713                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2714                                    + ps.name + "; removing system app.  Last known codePath="
2715                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2716                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2717                                    + scannedPkg.mVersionCode);
2718                            removePackageLI(scannedPkg, true);
2719                            mExpectingBetter.put(ps.name, ps.codePath);
2720                        }
2721
2722                        continue;
2723                    }
2724
2725                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2726                        psit.remove();
2727                        logCriticalInfo(Log.WARN, "System package " + ps.name
2728                                + " no longer exists; it's data will be wiped");
2729                        // Actual deletion of code and data will be handled by later
2730                        // reconciliation step
2731                    } else {
2732                        // we still have a disabled system package, but, it still might have
2733                        // been removed. check the code path still exists and check there's
2734                        // still a package. the latter can happen if an OTA keeps the same
2735                        // code path, but, changes the package name.
2736                        final PackageSetting disabledPs =
2737                                mSettings.getDisabledSystemPkgLPr(ps.name);
2738                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2739                                || disabledPs.pkg == null) {
2740                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2741                        }
2742                    }
2743                }
2744            }
2745
2746            //look for any incomplete package installations
2747            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2748            for (int i = 0; i < deletePkgsList.size(); i++) {
2749                // Actual deletion of code and data will be handled by later
2750                // reconciliation step
2751                final String packageName = deletePkgsList.get(i).name;
2752                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2753                synchronized (mPackages) {
2754                    mSettings.removePackageLPw(packageName);
2755                }
2756            }
2757
2758            //delete tmp files
2759            deleteTempPackageFiles();
2760
2761            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2762
2763            // Remove any shared userIDs that have no associated packages
2764            mSettings.pruneSharedUsersLPw();
2765            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2766            final int systemPackagesCount = mPackages.size();
2767            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2768                    + " ms, packageCount: " + systemPackagesCount
2769                    + " , timePerPackage: "
2770                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2771                    + " , cached: " + cachedSystemApps);
2772            if (mIsUpgrade && systemPackagesCount > 0) {
2773                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2774                        ((int) systemScanTime) / systemPackagesCount);
2775            }
2776            if (!mOnlyCore) {
2777                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2778                        SystemClock.uptimeMillis());
2779                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2780
2781                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2782                        | PackageParser.PARSE_FORWARD_LOCK,
2783                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2784
2785                // Remove disable package settings for updated system apps that were
2786                // removed via an OTA. If the update is no longer present, remove the
2787                // app completely. Otherwise, revoke their system privileges.
2788                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2789                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2790                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2791
2792                    final String msg;
2793                    if (deletedPkg == null) {
2794                        // should have found an update, but, we didn't; remove everything
2795                        msg = "Updated system package " + deletedAppName
2796                                + " no longer exists; removing its data";
2797                        // Actual deletion of code and data will be handled by later
2798                        // reconciliation step
2799                    } else {
2800                        // found an update; revoke system privileges
2801                        msg = "Updated system package + " + deletedAppName
2802                                + " no longer exists; revoking system privileges";
2803
2804                        // Don't do anything if a stub is removed from the system image. If
2805                        // we were to remove the uncompressed version from the /data partition,
2806                        // this is where it'd be done.
2807
2808                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2809                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2810                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2811                    }
2812                    logCriticalInfo(Log.WARN, msg);
2813                }
2814
2815                /*
2816                 * Make sure all system apps that we expected to appear on
2817                 * the userdata partition actually showed up. If they never
2818                 * appeared, crawl back and revive the system version.
2819                 */
2820                for (int i = 0; i < mExpectingBetter.size(); i++) {
2821                    final String packageName = mExpectingBetter.keyAt(i);
2822                    if (!mPackages.containsKey(packageName)) {
2823                        final File scanFile = mExpectingBetter.valueAt(i);
2824
2825                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2826                                + " but never showed up; reverting to system");
2827
2828                        int reparseFlags = mDefParseFlags;
2829                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2830                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2831                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2832                                    | PackageParser.PARSE_IS_PRIVILEGED;
2833                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2834                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2835                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2836                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2837                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2838                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2839                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2840                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2841                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2842                                    | PackageParser.PARSE_IS_OEM;
2843                        } else {
2844                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2845                            continue;
2846                        }
2847
2848                        mSettings.enableSystemPackageLPw(packageName);
2849
2850                        try {
2851                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2852                        } catch (PackageManagerException e) {
2853                            Slog.e(TAG, "Failed to parse original system package: "
2854                                    + e.getMessage());
2855                        }
2856                    }
2857                }
2858
2859                // Uncompress and install any stubbed system applications.
2860                // This must be done last to ensure all stubs are replaced or disabled.
2861                decompressSystemApplications(stubSystemApps, scanFlags);
2862
2863                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2864                                - cachedSystemApps;
2865
2866                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2867                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2868                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2869                        + " ms, packageCount: " + dataPackagesCount
2870                        + " , timePerPackage: "
2871                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2872                        + " , cached: " + cachedNonSystemApps);
2873                if (mIsUpgrade && dataPackagesCount > 0) {
2874                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2875                            ((int) dataScanTime) / dataPackagesCount);
2876                }
2877            }
2878            mExpectingBetter.clear();
2879
2880            // Resolve the storage manager.
2881            mStorageManagerPackage = getStorageManagerPackageName();
2882
2883            // Resolve protected action filters. Only the setup wizard is allowed to
2884            // have a high priority filter for these actions.
2885            mSetupWizardPackage = getSetupWizardPackageName();
2886            if (mProtectedFilters.size() > 0) {
2887                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2888                    Slog.i(TAG, "No setup wizard;"
2889                        + " All protected intents capped to priority 0");
2890                }
2891                for (ActivityIntentInfo filter : mProtectedFilters) {
2892                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2893                        if (DEBUG_FILTERS) {
2894                            Slog.i(TAG, "Found setup wizard;"
2895                                + " allow priority " + filter.getPriority() + ";"
2896                                + " package: " + filter.activity.info.packageName
2897                                + " activity: " + filter.activity.className
2898                                + " priority: " + filter.getPriority());
2899                        }
2900                        // skip setup wizard; allow it to keep the high priority filter
2901                        continue;
2902                    }
2903                    if (DEBUG_FILTERS) {
2904                        Slog.i(TAG, "Protected action; cap priority to 0;"
2905                                + " package: " + filter.activity.info.packageName
2906                                + " activity: " + filter.activity.className
2907                                + " origPrio: " + filter.getPriority());
2908                    }
2909                    filter.setPriority(0);
2910                }
2911            }
2912            mDeferProtectedFilters = false;
2913            mProtectedFilters.clear();
2914
2915            // Now that we know all of the shared libraries, update all clients to have
2916            // the correct library paths.
2917            updateAllSharedLibrariesLPw(null);
2918
2919            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2920                // NOTE: We ignore potential failures here during a system scan (like
2921                // the rest of the commands above) because there's precious little we
2922                // can do about it. A settings error is reported, though.
2923                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2924            }
2925
2926            // Now that we know all the packages we are keeping,
2927            // read and update their last usage times.
2928            mPackageUsage.read(mPackages);
2929            mCompilerStats.read();
2930
2931            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2932                    SystemClock.uptimeMillis());
2933            Slog.i(TAG, "Time to scan packages: "
2934                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2935                    + " seconds");
2936
2937            // If the platform SDK has changed since the last time we booted,
2938            // we need to re-grant app permission to catch any new ones that
2939            // appear.  This is really a hack, and means that apps can in some
2940            // cases get permissions that the user didn't initially explicitly
2941            // allow...  it would be nice to have some better way to handle
2942            // this situation.
2943            int updateFlags = UPDATE_PERMISSIONS_ALL;
2944            if (ver.sdkVersion != mSdkVersion) {
2945                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2946                        + mSdkVersion + "; regranting permissions for internal storage");
2947                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2948            }
2949            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2950            ver.sdkVersion = mSdkVersion;
2951
2952            // If this is the first boot or an update from pre-M, and it is a normal
2953            // boot, then we need to initialize the default preferred apps across
2954            // all defined users.
2955            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2956                for (UserInfo user : sUserManager.getUsers(true)) {
2957                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2958                    applyFactoryDefaultBrowserLPw(user.id);
2959                    primeDomainVerificationsLPw(user.id);
2960                }
2961            }
2962
2963            // Prepare storage for system user really early during boot,
2964            // since core system apps like SettingsProvider and SystemUI
2965            // can't wait for user to start
2966            final int storageFlags;
2967            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2968                storageFlags = StorageManager.FLAG_STORAGE_DE;
2969            } else {
2970                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2971            }
2972            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2973                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2974                    true /* onlyCoreApps */);
2975            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2976                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2977                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2978                traceLog.traceBegin("AppDataFixup");
2979                try {
2980                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2981                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2982                } catch (InstallerException e) {
2983                    Slog.w(TAG, "Trouble fixing GIDs", e);
2984                }
2985                traceLog.traceEnd();
2986
2987                traceLog.traceBegin("AppDataPrepare");
2988                if (deferPackages == null || deferPackages.isEmpty()) {
2989                    return;
2990                }
2991                int count = 0;
2992                for (String pkgName : deferPackages) {
2993                    PackageParser.Package pkg = null;
2994                    synchronized (mPackages) {
2995                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2996                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2997                            pkg = ps.pkg;
2998                        }
2999                    }
3000                    if (pkg != null) {
3001                        synchronized (mInstallLock) {
3002                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3003                                    true /* maybeMigrateAppData */);
3004                        }
3005                        count++;
3006                    }
3007                }
3008                traceLog.traceEnd();
3009                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3010            }, "prepareAppData");
3011
3012            // If this is first boot after an OTA, and a normal boot, then
3013            // we need to clear code cache directories.
3014            // Note that we do *not* clear the application profiles. These remain valid
3015            // across OTAs and are used to drive profile verification (post OTA) and
3016            // profile compilation (without waiting to collect a fresh set of profiles).
3017            if (mIsUpgrade && !onlyCore) {
3018                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3019                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3020                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3021                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3022                        // No apps are running this early, so no need to freeze
3023                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3024                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3025                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3026                    }
3027                }
3028                ver.fingerprint = Build.FINGERPRINT;
3029            }
3030
3031            checkDefaultBrowser();
3032
3033            // clear only after permissions and other defaults have been updated
3034            mExistingSystemPackages.clear();
3035            mPromoteSystemApps = false;
3036
3037            // All the changes are done during package scanning.
3038            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3039
3040            // can downgrade to reader
3041            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3042            mSettings.writeLPr();
3043            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3044            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3045                    SystemClock.uptimeMillis());
3046
3047            if (!mOnlyCore) {
3048                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3049                mRequiredInstallerPackage = getRequiredInstallerLPr();
3050                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3051                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3052                if (mIntentFilterVerifierComponent != null) {
3053                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3054                            mIntentFilterVerifierComponent);
3055                } else {
3056                    mIntentFilterVerifier = null;
3057                }
3058                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3059                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3060                        SharedLibraryInfo.VERSION_UNDEFINED);
3061                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3062                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3063                        SharedLibraryInfo.VERSION_UNDEFINED);
3064            } else {
3065                mRequiredVerifierPackage = null;
3066                mRequiredInstallerPackage = null;
3067                mRequiredUninstallerPackage = null;
3068                mIntentFilterVerifierComponent = null;
3069                mIntentFilterVerifier = null;
3070                mServicesSystemSharedLibraryPackageName = null;
3071                mSharedSystemSharedLibraryPackageName = null;
3072            }
3073
3074            mInstallerService = new PackageInstallerService(context, this);
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    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3204        if (DEBUG_COMPRESSION) {
3205            Slog.i(TAG, "Decompress file"
3206                    + "; src: " + srcFile.getAbsolutePath()
3207                    + ", dst: " + dstFile.getAbsolutePath());
3208        }
3209        try (
3210                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3211                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3212        ) {
3213            Streams.copy(fileIn, fileOut);
3214            Os.chmod(dstFile.getAbsolutePath(), 0644);
3215            return PackageManager.INSTALL_SUCCEEDED;
3216        } catch (IOException e) {
3217            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3218                    + "; src: " + srcFile.getAbsolutePath()
3219                    + ", dst: " + dstFile.getAbsolutePath());
3220        }
3221        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3222    }
3223
3224    private File[] getCompressedFiles(String codePath) {
3225        final File stubCodePath = new File(codePath);
3226        final String stubName = stubCodePath.getName();
3227
3228        // The layout of a compressed package on a given partition is as follows :
3229        //
3230        // Compressed artifacts:
3231        //
3232        // /partition/ModuleName/foo.gz
3233        // /partation/ModuleName/bar.gz
3234        //
3235        // Stub artifact:
3236        //
3237        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3238        //
3239        // In other words, stub is on the same partition as the compressed artifacts
3240        // and in a directory that's suffixed with "-Stub".
3241        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3242        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3243            return null;
3244        }
3245
3246        final File stubParentDir = stubCodePath.getParentFile();
3247        if (stubParentDir == null) {
3248            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3249            return null;
3250        }
3251
3252        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3253        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3254            @Override
3255            public boolean accept(File dir, String name) {
3256                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3257            }
3258        });
3259
3260        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3261            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3262        }
3263
3264        return files;
3265    }
3266
3267    private boolean compressedFileExists(String codePath) {
3268        final File[] compressedFiles = getCompressedFiles(codePath);
3269        return compressedFiles != null && compressedFiles.length > 0;
3270    }
3271
3272    /**
3273     * Decompresses the given package on the system image onto
3274     * the /data partition.
3275     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3276     */
3277    private File decompressPackage(PackageParser.Package pkg) {
3278        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3279        if (compressedFiles == null || compressedFiles.length == 0) {
3280            if (DEBUG_COMPRESSION) {
3281                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3282            }
3283            return null;
3284        }
3285        final File dstCodePath =
3286                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3287        int ret = PackageManager.INSTALL_SUCCEEDED;
3288        try {
3289            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3290            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3291            for (File srcFile : compressedFiles) {
3292                final String srcFileName = srcFile.getName();
3293                final String dstFileName = srcFileName.substring(
3294                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3295                final File dstFile = new File(dstCodePath, dstFileName);
3296                ret = decompressFile(srcFile, dstFile);
3297                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3298                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3299                            + "; pkg: " + pkg.packageName
3300                            + ", file: " + dstFileName);
3301                    break;
3302                }
3303            }
3304        } catch (ErrnoException e) {
3305            logCriticalInfo(Log.ERROR, "Failed to decompress"
3306                    + "; pkg: " + pkg.packageName
3307                    + ", err: " + e.errno);
3308        }
3309        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3310            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3311            NativeLibraryHelper.Handle handle = null;
3312            try {
3313                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3314                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3315                        null /*abiOverride*/);
3316            } catch (IOException e) {
3317                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3318                        + "; pkg: " + pkg.packageName);
3319                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3320            } finally {
3321                IoUtils.closeQuietly(handle);
3322            }
3323        }
3324        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3325            if (dstCodePath == null || !dstCodePath.exists()) {
3326                return null;
3327            }
3328            removeCodePathLI(dstCodePath);
3329            return null;
3330        }
3331        return dstCodePath;
3332    }
3333
3334    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3335        // we're only interested in updating the installer appliction when 1) it's not
3336        // already set or 2) the modified package is the installer
3337        if (mInstantAppInstallerActivity != null
3338                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3339                        .equals(modifiedPackage)) {
3340            return;
3341        }
3342        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3343    }
3344
3345    private static File preparePackageParserCache(boolean isUpgrade) {
3346        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3347            return null;
3348        }
3349
3350        // Disable package parsing on eng builds to allow for faster incremental development.
3351        if (Build.IS_ENG) {
3352            return null;
3353        }
3354
3355        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3356            Slog.i(TAG, "Disabling package parser cache due to system property.");
3357            return null;
3358        }
3359
3360        // The base directory for the package parser cache lives under /data/system/.
3361        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3362                "package_cache");
3363        if (cacheBaseDir == null) {
3364            return null;
3365        }
3366
3367        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3368        // This also serves to "GC" unused entries when the package cache version changes (which
3369        // can only happen during upgrades).
3370        if (isUpgrade) {
3371            FileUtils.deleteContents(cacheBaseDir);
3372        }
3373
3374
3375        // Return the versioned package cache directory. This is something like
3376        // "/data/system/package_cache/1"
3377        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3378
3379        // The following is a workaround to aid development on non-numbered userdebug
3380        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3381        // the system partition is newer.
3382        //
3383        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3384        // that starts with "eng." to signify that this is an engineering build and not
3385        // destined for release.
3386        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3387            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3388
3389            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3390            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3391            // in general and should not be used for production changes. In this specific case,
3392            // we know that they will work.
3393            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3394            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3395                FileUtils.deleteContents(cacheBaseDir);
3396                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3397            }
3398        }
3399
3400        return cacheDir;
3401    }
3402
3403    @Override
3404    public boolean isFirstBoot() {
3405        // allow instant applications
3406        return mFirstBoot;
3407    }
3408
3409    @Override
3410    public boolean isOnlyCoreApps() {
3411        // allow instant applications
3412        return mOnlyCore;
3413    }
3414
3415    @Override
3416    public boolean isUpgrade() {
3417        // allow instant applications
3418        return mIsUpgrade;
3419    }
3420
3421    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3422        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3423
3424        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3425                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3426                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3427        if (matches.size() == 1) {
3428            return matches.get(0).getComponentInfo().packageName;
3429        } else if (matches.size() == 0) {
3430            Log.e(TAG, "There should probably be a verifier, but, none were found");
3431            return null;
3432        }
3433        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3434    }
3435
3436    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3437        synchronized (mPackages) {
3438            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3439            if (libraryEntry == null) {
3440                throw new IllegalStateException("Missing required shared library:" + name);
3441            }
3442            return libraryEntry.apk;
3443        }
3444    }
3445
3446    private @NonNull String getRequiredInstallerLPr() {
3447        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3448        intent.addCategory(Intent.CATEGORY_DEFAULT);
3449        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3450
3451        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3452                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3453                UserHandle.USER_SYSTEM);
3454        if (matches.size() == 1) {
3455            ResolveInfo resolveInfo = matches.get(0);
3456            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3457                throw new RuntimeException("The installer must be a privileged app");
3458            }
3459            return matches.get(0).getComponentInfo().packageName;
3460        } else {
3461            throw new RuntimeException("There must be exactly one installer; found " + matches);
3462        }
3463    }
3464
3465    private @NonNull String getRequiredUninstallerLPr() {
3466        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3467        intent.addCategory(Intent.CATEGORY_DEFAULT);
3468        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3469
3470        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3471                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3472                UserHandle.USER_SYSTEM);
3473        if (resolveInfo == null ||
3474                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3475            throw new RuntimeException("There must be exactly one uninstaller; found "
3476                    + resolveInfo);
3477        }
3478        return resolveInfo.getComponentInfo().packageName;
3479    }
3480
3481    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3482        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3483
3484        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3485                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3486                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3487        ResolveInfo best = null;
3488        final int N = matches.size();
3489        for (int i = 0; i < N; i++) {
3490            final ResolveInfo cur = matches.get(i);
3491            final String packageName = cur.getComponentInfo().packageName;
3492            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3493                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3494                continue;
3495            }
3496
3497            if (best == null || cur.priority > best.priority) {
3498                best = cur;
3499            }
3500        }
3501
3502        if (best != null) {
3503            return best.getComponentInfo().getComponentName();
3504        }
3505        Slog.w(TAG, "Intent filter verifier not found");
3506        return null;
3507    }
3508
3509    @Override
3510    public @Nullable ComponentName getInstantAppResolverComponent() {
3511        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3512            return null;
3513        }
3514        synchronized (mPackages) {
3515            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3516            if (instantAppResolver == null) {
3517                return null;
3518            }
3519            return instantAppResolver.first;
3520        }
3521    }
3522
3523    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3524        final String[] packageArray =
3525                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3526        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3527            if (DEBUG_EPHEMERAL) {
3528                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3529            }
3530            return null;
3531        }
3532
3533        final int callingUid = Binder.getCallingUid();
3534        final int resolveFlags =
3535                MATCH_DIRECT_BOOT_AWARE
3536                | MATCH_DIRECT_BOOT_UNAWARE
3537                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3538        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3539        final Intent resolverIntent = new Intent(actionName);
3540        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3541                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3542        // temporarily look for the old action
3543        if (resolvers.size() == 0) {
3544            if (DEBUG_EPHEMERAL) {
3545                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3546            }
3547            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3548            resolverIntent.setAction(actionName);
3549            resolvers = queryIntentServicesInternal(resolverIntent, null,
3550                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3551        }
3552        final int N = resolvers.size();
3553        if (N == 0) {
3554            if (DEBUG_EPHEMERAL) {
3555                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3556            }
3557            return null;
3558        }
3559
3560        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3561        for (int i = 0; i < N; i++) {
3562            final ResolveInfo info = resolvers.get(i);
3563
3564            if (info.serviceInfo == null) {
3565                continue;
3566            }
3567
3568            final String packageName = info.serviceInfo.packageName;
3569            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3570                if (DEBUG_EPHEMERAL) {
3571                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3572                            + " pkg: " + packageName + ", info:" + info);
3573                }
3574                continue;
3575            }
3576
3577            if (DEBUG_EPHEMERAL) {
3578                Slog.v(TAG, "Ephemeral resolver found;"
3579                        + " pkg: " + packageName + ", info:" + info);
3580            }
3581            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3582        }
3583        if (DEBUG_EPHEMERAL) {
3584            Slog.v(TAG, "Ephemeral resolver NOT found");
3585        }
3586        return null;
3587    }
3588
3589    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3590        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3591        intent.addCategory(Intent.CATEGORY_DEFAULT);
3592        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3593
3594        final int resolveFlags =
3595                MATCH_DIRECT_BOOT_AWARE
3596                | MATCH_DIRECT_BOOT_UNAWARE
3597                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3598        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3599                resolveFlags, UserHandle.USER_SYSTEM);
3600        // temporarily look for the old action
3601        if (matches.isEmpty()) {
3602            if (DEBUG_EPHEMERAL) {
3603                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3604            }
3605            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3606            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3607                    resolveFlags, UserHandle.USER_SYSTEM);
3608        }
3609        Iterator<ResolveInfo> iter = matches.iterator();
3610        while (iter.hasNext()) {
3611            final ResolveInfo rInfo = iter.next();
3612            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3613            if (ps != null) {
3614                final PermissionsState permissionsState = ps.getPermissionsState();
3615                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3616                    continue;
3617                }
3618            }
3619            iter.remove();
3620        }
3621        if (matches.size() == 0) {
3622            return null;
3623        } else if (matches.size() == 1) {
3624            return (ActivityInfo) matches.get(0).getComponentInfo();
3625        } else {
3626            throw new RuntimeException(
3627                    "There must be at most one ephemeral installer; found " + matches);
3628        }
3629    }
3630
3631    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3632            @NonNull ComponentName resolver) {
3633        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3634                .addCategory(Intent.CATEGORY_DEFAULT)
3635                .setPackage(resolver.getPackageName());
3636        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3637        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3638                UserHandle.USER_SYSTEM);
3639        // temporarily look for the old action
3640        if (matches.isEmpty()) {
3641            if (DEBUG_EPHEMERAL) {
3642                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3643            }
3644            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3645            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3646                    UserHandle.USER_SYSTEM);
3647        }
3648        if (matches.isEmpty()) {
3649            return null;
3650        }
3651        return matches.get(0).getComponentInfo().getComponentName();
3652    }
3653
3654    private void primeDomainVerificationsLPw(int userId) {
3655        if (DEBUG_DOMAIN_VERIFICATION) {
3656            Slog.d(TAG, "Priming domain verifications in user " + userId);
3657        }
3658
3659        SystemConfig systemConfig = SystemConfig.getInstance();
3660        ArraySet<String> packages = systemConfig.getLinkedApps();
3661
3662        for (String packageName : packages) {
3663            PackageParser.Package pkg = mPackages.get(packageName);
3664            if (pkg != null) {
3665                if (!pkg.isSystemApp()) {
3666                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3667                    continue;
3668                }
3669
3670                ArraySet<String> domains = null;
3671                for (PackageParser.Activity a : pkg.activities) {
3672                    for (ActivityIntentInfo filter : a.intents) {
3673                        if (hasValidDomains(filter)) {
3674                            if (domains == null) {
3675                                domains = new ArraySet<String>();
3676                            }
3677                            domains.addAll(filter.getHostsList());
3678                        }
3679                    }
3680                }
3681
3682                if (domains != null && domains.size() > 0) {
3683                    if (DEBUG_DOMAIN_VERIFICATION) {
3684                        Slog.v(TAG, "      + " + packageName);
3685                    }
3686                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3687                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3688                    // and then 'always' in the per-user state actually used for intent resolution.
3689                    final IntentFilterVerificationInfo ivi;
3690                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3691                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3692                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3693                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3694                } else {
3695                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3696                            + "' does not handle web links");
3697                }
3698            } else {
3699                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3700            }
3701        }
3702
3703        scheduleWritePackageRestrictionsLocked(userId);
3704        scheduleWriteSettingsLocked();
3705    }
3706
3707    private void applyFactoryDefaultBrowserLPw(int userId) {
3708        // The default browser app's package name is stored in a string resource,
3709        // with a product-specific overlay used for vendor customization.
3710        String browserPkg = mContext.getResources().getString(
3711                com.android.internal.R.string.default_browser);
3712        if (!TextUtils.isEmpty(browserPkg)) {
3713            // non-empty string => required to be a known package
3714            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3715            if (ps == null) {
3716                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3717                browserPkg = null;
3718            } else {
3719                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3720            }
3721        }
3722
3723        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3724        // default.  If there's more than one, just leave everything alone.
3725        if (browserPkg == null) {
3726            calculateDefaultBrowserLPw(userId);
3727        }
3728    }
3729
3730    private void calculateDefaultBrowserLPw(int userId) {
3731        List<String> allBrowsers = resolveAllBrowserApps(userId);
3732        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3733        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3734    }
3735
3736    private List<String> resolveAllBrowserApps(int userId) {
3737        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3738        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3739                PackageManager.MATCH_ALL, userId);
3740
3741        final int count = list.size();
3742        List<String> result = new ArrayList<String>(count);
3743        for (int i=0; i<count; i++) {
3744            ResolveInfo info = list.get(i);
3745            if (info.activityInfo == null
3746                    || !info.handleAllWebDataURI
3747                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3748                    || result.contains(info.activityInfo.packageName)) {
3749                continue;
3750            }
3751            result.add(info.activityInfo.packageName);
3752        }
3753
3754        return result;
3755    }
3756
3757    private boolean packageIsBrowser(String packageName, int userId) {
3758        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3759                PackageManager.MATCH_ALL, userId);
3760        final int N = list.size();
3761        for (int i = 0; i < N; i++) {
3762            ResolveInfo info = list.get(i);
3763            if (packageName.equals(info.activityInfo.packageName)) {
3764                return true;
3765            }
3766        }
3767        return false;
3768    }
3769
3770    private void checkDefaultBrowser() {
3771        final int myUserId = UserHandle.myUserId();
3772        final String packageName = getDefaultBrowserPackageName(myUserId);
3773        if (packageName != null) {
3774            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3775            if (info == null) {
3776                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3777                synchronized (mPackages) {
3778                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3779                }
3780            }
3781        }
3782    }
3783
3784    @Override
3785    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3786            throws RemoteException {
3787        try {
3788            return super.onTransact(code, data, reply, flags);
3789        } catch (RuntimeException e) {
3790            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3791                Slog.wtf(TAG, "Package Manager Crash", e);
3792            }
3793            throw e;
3794        }
3795    }
3796
3797    static int[] appendInts(int[] cur, int[] add) {
3798        if (add == null) return cur;
3799        if (cur == null) return add;
3800        final int N = add.length;
3801        for (int i=0; i<N; i++) {
3802            cur = appendInt(cur, add[i]);
3803        }
3804        return cur;
3805    }
3806
3807    /**
3808     * Returns whether or not a full application can see an instant application.
3809     * <p>
3810     * Currently, there are three cases in which this can occur:
3811     * <ol>
3812     * <li>The calling application is a "special" process. The special
3813     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3814     *     and {@code 0}</li>
3815     * <li>The calling application has the permission
3816     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3817     * <li>The calling application is the default launcher on the
3818     *     system partition.</li>
3819     * </ol>
3820     */
3821    private boolean canViewInstantApps(int callingUid, int userId) {
3822        if (callingUid == Process.SYSTEM_UID
3823                || callingUid == Process.SHELL_UID
3824                || callingUid == Process.ROOT_UID) {
3825            return true;
3826        }
3827        if (mContext.checkCallingOrSelfPermission(
3828                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3829            return true;
3830        }
3831        if (mContext.checkCallingOrSelfPermission(
3832                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3833            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3834            if (homeComponent != null
3835                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3836                return true;
3837            }
3838        }
3839        return false;
3840    }
3841
3842    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3843        if (!sUserManager.exists(userId)) return null;
3844        if (ps == null) {
3845            return null;
3846        }
3847        PackageParser.Package p = ps.pkg;
3848        if (p == null) {
3849            return null;
3850        }
3851        final int callingUid = Binder.getCallingUid();
3852        // Filter out ephemeral app metadata:
3853        //   * The system/shell/root can see metadata for any app
3854        //   * An installed app can see metadata for 1) other installed apps
3855        //     and 2) ephemeral apps that have explicitly interacted with it
3856        //   * Ephemeral apps can only see their own data and exposed installed apps
3857        //   * Holding a signature permission allows seeing instant apps
3858        if (filterAppAccessLPr(ps, callingUid, userId)) {
3859            return null;
3860        }
3861
3862        final PermissionsState permissionsState = ps.getPermissionsState();
3863
3864        // Compute GIDs only if requested
3865        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3866                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3867        // Compute granted permissions only if package has requested permissions
3868        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3869                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3870        final PackageUserState state = ps.readUserState(userId);
3871
3872        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3873                && ps.isSystem()) {
3874            flags |= MATCH_ANY_USER;
3875        }
3876
3877        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3878                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3879
3880        if (packageInfo == null) {
3881            return null;
3882        }
3883
3884        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3885                resolveExternalPackageNameLPr(p);
3886
3887        return packageInfo;
3888    }
3889
3890    @Override
3891    public void checkPackageStartable(String packageName, int userId) {
3892        final int callingUid = Binder.getCallingUid();
3893        if (getInstantAppPackageName(callingUid) != null) {
3894            throw new SecurityException("Instant applications don't have access to this method");
3895        }
3896        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3897        synchronized (mPackages) {
3898            final PackageSetting ps = mSettings.mPackages.get(packageName);
3899            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3900                throw new SecurityException("Package " + packageName + " was not found!");
3901            }
3902
3903            if (!ps.getInstalled(userId)) {
3904                throw new SecurityException(
3905                        "Package " + packageName + " was not installed for user " + userId + "!");
3906            }
3907
3908            if (mSafeMode && !ps.isSystem()) {
3909                throw new SecurityException("Package " + packageName + " not a system app!");
3910            }
3911
3912            if (mFrozenPackages.contains(packageName)) {
3913                throw new SecurityException("Package " + packageName + " is currently frozen!");
3914            }
3915
3916            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3917                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3918            }
3919        }
3920    }
3921
3922    @Override
3923    public boolean isPackageAvailable(String packageName, int userId) {
3924        if (!sUserManager.exists(userId)) return false;
3925        final int callingUid = Binder.getCallingUid();
3926        enforceCrossUserPermission(callingUid, userId,
3927                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3928        synchronized (mPackages) {
3929            PackageParser.Package p = mPackages.get(packageName);
3930            if (p != null) {
3931                final PackageSetting ps = (PackageSetting) p.mExtras;
3932                if (filterAppAccessLPr(ps, callingUid, userId)) {
3933                    return false;
3934                }
3935                if (ps != null) {
3936                    final PackageUserState state = ps.readUserState(userId);
3937                    if (state != null) {
3938                        return PackageParser.isAvailable(state);
3939                    }
3940                }
3941            }
3942        }
3943        return false;
3944    }
3945
3946    @Override
3947    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3948        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3949                flags, Binder.getCallingUid(), userId);
3950    }
3951
3952    @Override
3953    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3954            int flags, int userId) {
3955        return getPackageInfoInternal(versionedPackage.getPackageName(),
3956                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3957    }
3958
3959    /**
3960     * Important: The provided filterCallingUid is used exclusively to filter out packages
3961     * that can be seen based on user state. It's typically the original caller uid prior
3962     * to clearing. Because it can only be provided by trusted code, it's value can be
3963     * trusted and will be used as-is; unlike userId which will be validated by this method.
3964     */
3965    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3966            int flags, int filterCallingUid, int userId) {
3967        if (!sUserManager.exists(userId)) return null;
3968        flags = updateFlagsForPackage(flags, userId, packageName);
3969        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3970                false /* requireFullPermission */, false /* checkShell */, "get package info");
3971
3972        // reader
3973        synchronized (mPackages) {
3974            // Normalize package name to handle renamed packages and static libs
3975            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3976
3977            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3978            if (matchFactoryOnly) {
3979                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3980                if (ps != null) {
3981                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3982                        return null;
3983                    }
3984                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3985                        return null;
3986                    }
3987                    return generatePackageInfo(ps, flags, userId);
3988                }
3989            }
3990
3991            PackageParser.Package p = mPackages.get(packageName);
3992            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3993                return null;
3994            }
3995            if (DEBUG_PACKAGE_INFO)
3996                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3997            if (p != null) {
3998                final PackageSetting ps = (PackageSetting) p.mExtras;
3999                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4000                    return null;
4001                }
4002                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4003                    return null;
4004                }
4005                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4006            }
4007            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4008                final PackageSetting ps = mSettings.mPackages.get(packageName);
4009                if (ps == null) return null;
4010                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4011                    return null;
4012                }
4013                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4014                    return null;
4015                }
4016                return generatePackageInfo(ps, flags, userId);
4017            }
4018        }
4019        return null;
4020    }
4021
4022    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4023        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4024            return true;
4025        }
4026        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4027            return true;
4028        }
4029        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4030            return true;
4031        }
4032        return false;
4033    }
4034
4035    private boolean isComponentVisibleToInstantApp(
4036            @Nullable ComponentName component, @ComponentType int type) {
4037        if (type == TYPE_ACTIVITY) {
4038            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4039            return activity != null
4040                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4041                    : false;
4042        } else if (type == TYPE_RECEIVER) {
4043            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4044            return activity != null
4045                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4046                    : false;
4047        } else if (type == TYPE_SERVICE) {
4048            final PackageParser.Service service = mServices.mServices.get(component);
4049            return service != null
4050                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4051                    : false;
4052        } else if (type == TYPE_PROVIDER) {
4053            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4054            return provider != null
4055                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4056                    : false;
4057        } else if (type == TYPE_UNKNOWN) {
4058            return isComponentVisibleToInstantApp(component);
4059        }
4060        return false;
4061    }
4062
4063    /**
4064     * Returns whether or not access to the application should be filtered.
4065     * <p>
4066     * Access may be limited based upon whether the calling or target applications
4067     * are instant applications.
4068     *
4069     * @see #canAccessInstantApps(int)
4070     */
4071    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4072            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4073        // if we're in an isolated process, get the real calling UID
4074        if (Process.isIsolated(callingUid)) {
4075            callingUid = mIsolatedOwners.get(callingUid);
4076        }
4077        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4078        final boolean callerIsInstantApp = instantAppPkgName != null;
4079        if (ps == null) {
4080            if (callerIsInstantApp) {
4081                // pretend the application exists, but, needs to be filtered
4082                return true;
4083            }
4084            return false;
4085        }
4086        // if the target and caller are the same application, don't filter
4087        if (isCallerSameApp(ps.name, callingUid)) {
4088            return false;
4089        }
4090        if (callerIsInstantApp) {
4091            // request for a specific component; if it hasn't been explicitly exposed, filter
4092            if (component != null) {
4093                return !isComponentVisibleToInstantApp(component, componentType);
4094            }
4095            // request for application; if no components have been explicitly exposed, filter
4096            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4097        }
4098        if (ps.getInstantApp(userId)) {
4099            // caller can see all components of all instant applications, don't filter
4100            if (canViewInstantApps(callingUid, userId)) {
4101                return false;
4102            }
4103            // request for a specific instant application component, filter
4104            if (component != null) {
4105                return true;
4106            }
4107            // request for an instant application; if the caller hasn't been granted access, filter
4108            return !mInstantAppRegistry.isInstantAccessGranted(
4109                    userId, UserHandle.getAppId(callingUid), ps.appId);
4110        }
4111        return false;
4112    }
4113
4114    /**
4115     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4116     */
4117    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4118        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4119    }
4120
4121    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4122            int flags) {
4123        // Callers can access only the libs they depend on, otherwise they need to explicitly
4124        // ask for the shared libraries given the caller is allowed to access all static libs.
4125        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4126            // System/shell/root get to see all static libs
4127            final int appId = UserHandle.getAppId(uid);
4128            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4129                    || appId == Process.ROOT_UID) {
4130                return false;
4131            }
4132        }
4133
4134        // No package means no static lib as it is always on internal storage
4135        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4136            return false;
4137        }
4138
4139        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4140                ps.pkg.staticSharedLibVersion);
4141        if (libEntry == null) {
4142            return false;
4143        }
4144
4145        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4146        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4147        if (uidPackageNames == null) {
4148            return true;
4149        }
4150
4151        for (String uidPackageName : uidPackageNames) {
4152            if (ps.name.equals(uidPackageName)) {
4153                return false;
4154            }
4155            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4156            if (uidPs != null) {
4157                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4158                        libEntry.info.getName());
4159                if (index < 0) {
4160                    continue;
4161                }
4162                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4163                    return false;
4164                }
4165            }
4166        }
4167        return true;
4168    }
4169
4170    @Override
4171    public String[] currentToCanonicalPackageNames(String[] names) {
4172        final int callingUid = Binder.getCallingUid();
4173        if (getInstantAppPackageName(callingUid) != null) {
4174            return names;
4175        }
4176        final String[] out = new String[names.length];
4177        // reader
4178        synchronized (mPackages) {
4179            final int callingUserId = UserHandle.getUserId(callingUid);
4180            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4181            for (int i=names.length-1; i>=0; i--) {
4182                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4183                boolean translateName = false;
4184                if (ps != null && ps.realName != null) {
4185                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4186                    translateName = !targetIsInstantApp
4187                            || canViewInstantApps
4188                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4189                                    UserHandle.getAppId(callingUid), ps.appId);
4190                }
4191                out[i] = translateName ? ps.realName : names[i];
4192            }
4193        }
4194        return out;
4195    }
4196
4197    @Override
4198    public String[] canonicalToCurrentPackageNames(String[] names) {
4199        final int callingUid = Binder.getCallingUid();
4200        if (getInstantAppPackageName(callingUid) != null) {
4201            return names;
4202        }
4203        final String[] out = new String[names.length];
4204        // reader
4205        synchronized (mPackages) {
4206            final int callingUserId = UserHandle.getUserId(callingUid);
4207            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4208            for (int i=names.length-1; i>=0; i--) {
4209                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4210                boolean translateName = false;
4211                if (cur != null) {
4212                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4213                    final boolean targetIsInstantApp =
4214                            ps != null && ps.getInstantApp(callingUserId);
4215                    translateName = !targetIsInstantApp
4216                            || canViewInstantApps
4217                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4218                                    UserHandle.getAppId(callingUid), ps.appId);
4219                }
4220                out[i] = translateName ? cur : names[i];
4221            }
4222        }
4223        return out;
4224    }
4225
4226    @Override
4227    public int getPackageUid(String packageName, int flags, int userId) {
4228        if (!sUserManager.exists(userId)) return -1;
4229        final int callingUid = Binder.getCallingUid();
4230        flags = updateFlagsForPackage(flags, userId, packageName);
4231        enforceCrossUserPermission(callingUid, userId,
4232                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4233
4234        // reader
4235        synchronized (mPackages) {
4236            final PackageParser.Package p = mPackages.get(packageName);
4237            if (p != null && p.isMatch(flags)) {
4238                PackageSetting ps = (PackageSetting) p.mExtras;
4239                if (filterAppAccessLPr(ps, callingUid, userId)) {
4240                    return -1;
4241                }
4242                return UserHandle.getUid(userId, p.applicationInfo.uid);
4243            }
4244            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4245                final PackageSetting ps = mSettings.mPackages.get(packageName);
4246                if (ps != null && ps.isMatch(flags)
4247                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4248                    return UserHandle.getUid(userId, ps.appId);
4249                }
4250            }
4251        }
4252
4253        return -1;
4254    }
4255
4256    @Override
4257    public int[] getPackageGids(String packageName, int flags, int userId) {
4258        if (!sUserManager.exists(userId)) return null;
4259        final int callingUid = Binder.getCallingUid();
4260        flags = updateFlagsForPackage(flags, userId, packageName);
4261        enforceCrossUserPermission(callingUid, userId,
4262                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4263
4264        // reader
4265        synchronized (mPackages) {
4266            final PackageParser.Package p = mPackages.get(packageName);
4267            if (p != null && p.isMatch(flags)) {
4268                PackageSetting ps = (PackageSetting) p.mExtras;
4269                if (filterAppAccessLPr(ps, callingUid, userId)) {
4270                    return null;
4271                }
4272                // TODO: Shouldn't this be checking for package installed state for userId and
4273                // return null?
4274                return ps.getPermissionsState().computeGids(userId);
4275            }
4276            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4277                final PackageSetting ps = mSettings.mPackages.get(packageName);
4278                if (ps != null && ps.isMatch(flags)
4279                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4280                    return ps.getPermissionsState().computeGids(userId);
4281                }
4282            }
4283        }
4284
4285        return null;
4286    }
4287
4288    @Override
4289    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4290        final int callingUid = Binder.getCallingUid();
4291        if (getInstantAppPackageName(callingUid) != null) {
4292            return null;
4293        }
4294        // reader
4295        synchronized (mPackages) {
4296            final BasePermission bp = mSettings.mPermissions.get(name);
4297            if (bp == null) {
4298                return null;
4299            }
4300            final int adjustedProtectionLevel = adjustPermissionProtectionFlagsLPr(
4301                    bp.getProtectionLevel(), packageName, callingUid);
4302            return bp.generatePermissionInfo(adjustedProtectionLevel, flags);
4303        }
4304    }
4305
4306    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4307            String packageName, int uid) {
4308        // Signature permission flags area always reported
4309        final int protectionLevelMasked = protectionLevel
4310                & (PermissionInfo.PROTECTION_NORMAL
4311                | PermissionInfo.PROTECTION_DANGEROUS
4312                | PermissionInfo.PROTECTION_SIGNATURE);
4313        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4314            return protectionLevel;
4315        }
4316
4317        // System sees all flags.
4318        final int appId = UserHandle.getAppId(uid);
4319        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4320                || appId == Process.SHELL_UID) {
4321            return protectionLevel;
4322        }
4323
4324        // Normalize package name to handle renamed packages and static libs
4325        packageName = resolveInternalPackageNameLPr(packageName,
4326                PackageManager.VERSION_CODE_HIGHEST);
4327
4328        // Apps that target O see flags for all protection levels.
4329        final PackageSetting ps = mSettings.mPackages.get(packageName);
4330        if (ps == null) {
4331            return protectionLevel;
4332        }
4333        if (ps.appId != appId) {
4334            return protectionLevel;
4335        }
4336
4337        final PackageParser.Package pkg = mPackages.get(packageName);
4338        if (pkg == null) {
4339            return protectionLevel;
4340        }
4341        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4342            return protectionLevelMasked;
4343        }
4344
4345        return protectionLevel;
4346    }
4347
4348    @Override
4349    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4350            int flags) {
4351        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4352            return null;
4353        }
4354        // reader
4355        synchronized (mPackages) {
4356            if (groupName != null && !mPermissionGroups.containsKey(groupName)) {
4357                // This is thrown as NameNotFoundException
4358                return null;
4359            }
4360
4361            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4362            for (BasePermission bp : mSettings.mPermissions.values()) {
4363                final PermissionInfo pi = bp.generatePermissionInfo(groupName, flags);
4364                if (pi != null) {
4365                    out.add(pi);
4366                }
4367            }
4368            return new ParceledListSlice<>(out);
4369        }
4370    }
4371
4372    @Override
4373    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4374        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4375            return null;
4376        }
4377        // reader
4378        synchronized (mPackages) {
4379            return PackageParser.generatePermissionGroupInfo(
4380                    mPermissionGroups.get(name), flags);
4381        }
4382    }
4383
4384    @Override
4385    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4386        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4387            return ParceledListSlice.emptyList();
4388        }
4389        // reader
4390        synchronized (mPackages) {
4391            final int N = mPermissionGroups.size();
4392            ArrayList<PermissionGroupInfo> out
4393                    = new ArrayList<PermissionGroupInfo>(N);
4394            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4395                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4396            }
4397            return new ParceledListSlice<>(out);
4398        }
4399    }
4400
4401    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4402            int filterCallingUid, int userId) {
4403        if (!sUserManager.exists(userId)) return null;
4404        PackageSetting ps = mSettings.mPackages.get(packageName);
4405        if (ps != null) {
4406            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4407                return null;
4408            }
4409            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4410                return null;
4411            }
4412            if (ps.pkg == null) {
4413                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4414                if (pInfo != null) {
4415                    return pInfo.applicationInfo;
4416                }
4417                return null;
4418            }
4419            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4420                    ps.readUserState(userId), userId);
4421            if (ai != null) {
4422                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4423            }
4424            return ai;
4425        }
4426        return null;
4427    }
4428
4429    @Override
4430    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4431        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4432    }
4433
4434    /**
4435     * Important: The provided filterCallingUid is used exclusively to filter out applications
4436     * that can be seen based on user state. It's typically the original caller uid prior
4437     * to clearing. Because it can only be provided by trusted code, it's value can be
4438     * trusted and will be used as-is; unlike userId which will be validated by this method.
4439     */
4440    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4441            int filterCallingUid, int userId) {
4442        if (!sUserManager.exists(userId)) return null;
4443        flags = updateFlagsForApplication(flags, userId, packageName);
4444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4445                false /* requireFullPermission */, false /* checkShell */, "get application info");
4446
4447        // writer
4448        synchronized (mPackages) {
4449            // Normalize package name to handle renamed packages and static libs
4450            packageName = resolveInternalPackageNameLPr(packageName,
4451                    PackageManager.VERSION_CODE_HIGHEST);
4452
4453            PackageParser.Package p = mPackages.get(packageName);
4454            if (DEBUG_PACKAGE_INFO) Log.v(
4455                    TAG, "getApplicationInfo " + packageName
4456                    + ": " + p);
4457            if (p != null) {
4458                PackageSetting ps = mSettings.mPackages.get(packageName);
4459                if (ps == null) return null;
4460                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4461                    return null;
4462                }
4463                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4464                    return null;
4465                }
4466                // Note: isEnabledLP() does not apply here - always return info
4467                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4468                        p, flags, ps.readUserState(userId), userId);
4469                if (ai != null) {
4470                    ai.packageName = resolveExternalPackageNameLPr(p);
4471                }
4472                return ai;
4473            }
4474            if ("android".equals(packageName)||"system".equals(packageName)) {
4475                return mAndroidApplication;
4476            }
4477            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4478                // Already generates the external package name
4479                return generateApplicationInfoFromSettingsLPw(packageName,
4480                        flags, filterCallingUid, userId);
4481            }
4482        }
4483        return null;
4484    }
4485
4486    private String normalizePackageNameLPr(String packageName) {
4487        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4488        return normalizedPackageName != null ? normalizedPackageName : packageName;
4489    }
4490
4491    @Override
4492    public void deletePreloadsFileCache() {
4493        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4494            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4495        }
4496        File dir = Environment.getDataPreloadsFileCacheDirectory();
4497        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4498        FileUtils.deleteContents(dir);
4499    }
4500
4501    @Override
4502    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4503            final int storageFlags, final IPackageDataObserver observer) {
4504        mContext.enforceCallingOrSelfPermission(
4505                android.Manifest.permission.CLEAR_APP_CACHE, null);
4506        mHandler.post(() -> {
4507            boolean success = false;
4508            try {
4509                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4510                success = true;
4511            } catch (IOException e) {
4512                Slog.w(TAG, e);
4513            }
4514            if (observer != null) {
4515                try {
4516                    observer.onRemoveCompleted(null, success);
4517                } catch (RemoteException e) {
4518                    Slog.w(TAG, e);
4519                }
4520            }
4521        });
4522    }
4523
4524    @Override
4525    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4526            final int storageFlags, final IntentSender pi) {
4527        mContext.enforceCallingOrSelfPermission(
4528                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4529        mHandler.post(() -> {
4530            boolean success = false;
4531            try {
4532                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4533                success = true;
4534            } catch (IOException e) {
4535                Slog.w(TAG, e);
4536            }
4537            if (pi != null) {
4538                try {
4539                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4540                } catch (SendIntentException e) {
4541                    Slog.w(TAG, e);
4542                }
4543            }
4544        });
4545    }
4546
4547    /**
4548     * Blocking call to clear various types of cached data across the system
4549     * until the requested bytes are available.
4550     */
4551    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4552        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4553        final File file = storage.findPathForUuid(volumeUuid);
4554        if (file.getUsableSpace() >= bytes) return;
4555
4556        if (ENABLE_FREE_CACHE_V2) {
4557            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4558                    volumeUuid);
4559            final boolean aggressive = (storageFlags
4560                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4561            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4562
4563            // 1. Pre-flight to determine if we have any chance to succeed
4564            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4565            if (internalVolume && (aggressive || SystemProperties
4566                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4567                deletePreloadsFileCache();
4568                if (file.getUsableSpace() >= bytes) return;
4569            }
4570
4571            // 3. Consider parsed APK data (aggressive only)
4572            if (internalVolume && aggressive) {
4573                FileUtils.deleteContents(mCacheDir);
4574                if (file.getUsableSpace() >= bytes) return;
4575            }
4576
4577            // 4. Consider cached app data (above quotas)
4578            try {
4579                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4580                        Installer.FLAG_FREE_CACHE_V2);
4581            } catch (InstallerException ignored) {
4582            }
4583            if (file.getUsableSpace() >= bytes) return;
4584
4585            // 5. Consider shared libraries with refcount=0 and age>min cache period
4586            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4587                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4588                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4589                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4590                return;
4591            }
4592
4593            // 6. Consider dexopt output (aggressive only)
4594            // TODO: Implement
4595
4596            // 7. Consider installed instant apps unused longer than min cache period
4597            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4598                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4599                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4600                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4601                return;
4602            }
4603
4604            // 8. Consider cached app data (below quotas)
4605            try {
4606                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4607                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4608            } catch (InstallerException ignored) {
4609            }
4610            if (file.getUsableSpace() >= bytes) return;
4611
4612            // 9. Consider DropBox entries
4613            // TODO: Implement
4614
4615            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4616            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4617                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4618                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4619                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4620                return;
4621            }
4622        } else {
4623            try {
4624                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4625            } catch (InstallerException ignored) {
4626            }
4627            if (file.getUsableSpace() >= bytes) return;
4628        }
4629
4630        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4631    }
4632
4633    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4634            throws IOException {
4635        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4636        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4637
4638        List<VersionedPackage> packagesToDelete = null;
4639        final long now = System.currentTimeMillis();
4640
4641        synchronized (mPackages) {
4642            final int[] allUsers = sUserManager.getUserIds();
4643            final int libCount = mSharedLibraries.size();
4644            for (int i = 0; i < libCount; i++) {
4645                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4646                if (versionedLib == null) {
4647                    continue;
4648                }
4649                final int versionCount = versionedLib.size();
4650                for (int j = 0; j < versionCount; j++) {
4651                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4652                    // Skip packages that are not static shared libs.
4653                    if (!libInfo.isStatic()) {
4654                        break;
4655                    }
4656                    // Important: We skip static shared libs used for some user since
4657                    // in such a case we need to keep the APK on the device. The check for
4658                    // a lib being used for any user is performed by the uninstall call.
4659                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4660                    // Resolve the package name - we use synthetic package names internally
4661                    final String internalPackageName = resolveInternalPackageNameLPr(
4662                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4663                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4664                    // Skip unused static shared libs cached less than the min period
4665                    // to prevent pruning a lib needed by a subsequently installed package.
4666                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4667                        continue;
4668                    }
4669                    if (packagesToDelete == null) {
4670                        packagesToDelete = new ArrayList<>();
4671                    }
4672                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4673                            declaringPackage.getVersionCode()));
4674                }
4675            }
4676        }
4677
4678        if (packagesToDelete != null) {
4679            final int packageCount = packagesToDelete.size();
4680            for (int i = 0; i < packageCount; i++) {
4681                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4682                // Delete the package synchronously (will fail of the lib used for any user).
4683                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4684                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4685                                == PackageManager.DELETE_SUCCEEDED) {
4686                    if (volume.getUsableSpace() >= neededSpace) {
4687                        return true;
4688                    }
4689                }
4690            }
4691        }
4692
4693        return false;
4694    }
4695
4696    /**
4697     * Update given flags based on encryption status of current user.
4698     */
4699    private int updateFlags(int flags, int userId) {
4700        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4701                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4702            // Caller expressed an explicit opinion about what encryption
4703            // aware/unaware components they want to see, so fall through and
4704            // give them what they want
4705        } else {
4706            // Caller expressed no opinion, so match based on user state
4707            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4708                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4709            } else {
4710                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4711            }
4712        }
4713        return flags;
4714    }
4715
4716    private UserManagerInternal getUserManagerInternal() {
4717        if (mUserManagerInternal == null) {
4718            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4719        }
4720        return mUserManagerInternal;
4721    }
4722
4723    private DeviceIdleController.LocalService getDeviceIdleController() {
4724        if (mDeviceIdleController == null) {
4725            mDeviceIdleController =
4726                    LocalServices.getService(DeviceIdleController.LocalService.class);
4727        }
4728        return mDeviceIdleController;
4729    }
4730
4731    /**
4732     * Update given flags when being used to request {@link PackageInfo}.
4733     */
4734    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4735        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4736        boolean triaged = true;
4737        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4738                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4739            // Caller is asking for component details, so they'd better be
4740            // asking for specific encryption matching behavior, or be triaged
4741            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4742                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4743                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4744                triaged = false;
4745            }
4746        }
4747        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4748                | PackageManager.MATCH_SYSTEM_ONLY
4749                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4750            triaged = false;
4751        }
4752        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4753            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4754                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4755                    + Debug.getCallers(5));
4756        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4757                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4758            // If the caller wants all packages and has a restricted profile associated with it,
4759            // then match all users. This is to make sure that launchers that need to access work
4760            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4761            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4762            flags |= PackageManager.MATCH_ANY_USER;
4763        }
4764        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4765            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4766                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4767        }
4768        return updateFlags(flags, userId);
4769    }
4770
4771    /**
4772     * Update given flags when being used to request {@link ApplicationInfo}.
4773     */
4774    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4775        return updateFlagsForPackage(flags, userId, cookie);
4776    }
4777
4778    /**
4779     * Update given flags when being used to request {@link ComponentInfo}.
4780     */
4781    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4782        if (cookie instanceof Intent) {
4783            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4784                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4785            }
4786        }
4787
4788        boolean triaged = true;
4789        // Caller is asking for component details, so they'd better be
4790        // asking for specific encryption matching behavior, or be triaged
4791        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4792                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4793                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4794            triaged = false;
4795        }
4796        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4797            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4798                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4799        }
4800
4801        return updateFlags(flags, userId);
4802    }
4803
4804    /**
4805     * Update given intent when being used to request {@link ResolveInfo}.
4806     */
4807    private Intent updateIntentForResolve(Intent intent) {
4808        if (intent.getSelector() != null) {
4809            intent = intent.getSelector();
4810        }
4811        if (DEBUG_PREFERRED) {
4812            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4813        }
4814        return intent;
4815    }
4816
4817    /**
4818     * Update given flags when being used to request {@link ResolveInfo}.
4819     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4820     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4821     * flag set. However, this flag is only honoured in three circumstances:
4822     * <ul>
4823     * <li>when called from a system process</li>
4824     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4825     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4826     * action and a {@code android.intent.category.BROWSABLE} category</li>
4827     * </ul>
4828     */
4829    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4830        return updateFlagsForResolve(flags, userId, intent, callingUid,
4831                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4832    }
4833    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4834            boolean wantInstantApps) {
4835        return updateFlagsForResolve(flags, userId, intent, callingUid,
4836                wantInstantApps, false /*onlyExposedExplicitly*/);
4837    }
4838    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4839            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4840        // Safe mode means we shouldn't match any third-party components
4841        if (mSafeMode) {
4842            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4843        }
4844        if (getInstantAppPackageName(callingUid) != null) {
4845            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4846            if (onlyExposedExplicitly) {
4847                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4848            }
4849            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4850            flags |= PackageManager.MATCH_INSTANT;
4851        } else {
4852            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4853            final boolean allowMatchInstant =
4854                    (wantInstantApps
4855                            && Intent.ACTION_VIEW.equals(intent.getAction())
4856                            && hasWebURI(intent))
4857                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4858            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4859                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4860            if (!allowMatchInstant) {
4861                flags &= ~PackageManager.MATCH_INSTANT;
4862            }
4863        }
4864        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4865    }
4866
4867    @Override
4868    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4869        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4870    }
4871
4872    /**
4873     * Important: The provided filterCallingUid is used exclusively to filter out activities
4874     * that can be seen based on user state. It's typically the original caller uid prior
4875     * to clearing. Because it can only be provided by trusted code, it's value can be
4876     * trusted and will be used as-is; unlike userId which will be validated by this method.
4877     */
4878    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4879            int filterCallingUid, int userId) {
4880        if (!sUserManager.exists(userId)) return null;
4881        flags = updateFlagsForComponent(flags, userId, component);
4882        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4883                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4884        synchronized (mPackages) {
4885            PackageParser.Activity a = mActivities.mActivities.get(component);
4886
4887            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4888            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4889                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4890                if (ps == null) return null;
4891                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4892                    return null;
4893                }
4894                return PackageParser.generateActivityInfo(
4895                        a, flags, ps.readUserState(userId), userId);
4896            }
4897            if (mResolveComponentName.equals(component)) {
4898                return PackageParser.generateActivityInfo(
4899                        mResolveActivity, flags, new PackageUserState(), userId);
4900            }
4901        }
4902        return null;
4903    }
4904
4905    @Override
4906    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4907            String resolvedType) {
4908        synchronized (mPackages) {
4909            if (component.equals(mResolveComponentName)) {
4910                // The resolver supports EVERYTHING!
4911                return true;
4912            }
4913            final int callingUid = Binder.getCallingUid();
4914            final int callingUserId = UserHandle.getUserId(callingUid);
4915            PackageParser.Activity a = mActivities.mActivities.get(component);
4916            if (a == null) {
4917                return false;
4918            }
4919            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4920            if (ps == null) {
4921                return false;
4922            }
4923            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4924                return false;
4925            }
4926            for (int i=0; i<a.intents.size(); i++) {
4927                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4928                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4929                    return true;
4930                }
4931            }
4932            return false;
4933        }
4934    }
4935
4936    @Override
4937    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4938        if (!sUserManager.exists(userId)) return null;
4939        final int callingUid = Binder.getCallingUid();
4940        flags = updateFlagsForComponent(flags, userId, component);
4941        enforceCrossUserPermission(callingUid, userId,
4942                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4943        synchronized (mPackages) {
4944            PackageParser.Activity a = mReceivers.mActivities.get(component);
4945            if (DEBUG_PACKAGE_INFO) Log.v(
4946                TAG, "getReceiverInfo " + component + ": " + a);
4947            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4948                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4949                if (ps == null) return null;
4950                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4951                    return null;
4952                }
4953                return PackageParser.generateActivityInfo(
4954                        a, flags, ps.readUserState(userId), userId);
4955            }
4956        }
4957        return null;
4958    }
4959
4960    @Override
4961    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4962            int flags, int userId) {
4963        if (!sUserManager.exists(userId)) return null;
4964        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4965        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4966            return null;
4967        }
4968
4969        flags = updateFlagsForPackage(flags, userId, null);
4970
4971        final boolean canSeeStaticLibraries =
4972                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4973                        == PERMISSION_GRANTED
4974                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4975                        == PERMISSION_GRANTED
4976                || canRequestPackageInstallsInternal(packageName,
4977                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4978                        false  /* throwIfPermNotDeclared*/)
4979                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4980                        == PERMISSION_GRANTED;
4981
4982        synchronized (mPackages) {
4983            List<SharedLibraryInfo> result = null;
4984
4985            final int libCount = mSharedLibraries.size();
4986            for (int i = 0; i < libCount; i++) {
4987                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4988                if (versionedLib == null) {
4989                    continue;
4990                }
4991
4992                final int versionCount = versionedLib.size();
4993                for (int j = 0; j < versionCount; j++) {
4994                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4995                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4996                        break;
4997                    }
4998                    final long identity = Binder.clearCallingIdentity();
4999                    try {
5000                        PackageInfo packageInfo = getPackageInfoVersioned(
5001                                libInfo.getDeclaringPackage(), flags
5002                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5003                        if (packageInfo == null) {
5004                            continue;
5005                        }
5006                    } finally {
5007                        Binder.restoreCallingIdentity(identity);
5008                    }
5009
5010                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5011                            libInfo.getVersion(), libInfo.getType(),
5012                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5013                            flags, userId));
5014
5015                    if (result == null) {
5016                        result = new ArrayList<>();
5017                    }
5018                    result.add(resLibInfo);
5019                }
5020            }
5021
5022            return result != null ? new ParceledListSlice<>(result) : null;
5023        }
5024    }
5025
5026    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5027            SharedLibraryInfo libInfo, int flags, int userId) {
5028        List<VersionedPackage> versionedPackages = null;
5029        final int packageCount = mSettings.mPackages.size();
5030        for (int i = 0; i < packageCount; i++) {
5031            PackageSetting ps = mSettings.mPackages.valueAt(i);
5032
5033            if (ps == null) {
5034                continue;
5035            }
5036
5037            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5038                continue;
5039            }
5040
5041            final String libName = libInfo.getName();
5042            if (libInfo.isStatic()) {
5043                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5044                if (libIdx < 0) {
5045                    continue;
5046                }
5047                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5048                    continue;
5049                }
5050                if (versionedPackages == null) {
5051                    versionedPackages = new ArrayList<>();
5052                }
5053                // If the dependent is a static shared lib, use the public package name
5054                String dependentPackageName = ps.name;
5055                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5056                    dependentPackageName = ps.pkg.manifestPackageName;
5057                }
5058                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5059            } else if (ps.pkg != null) {
5060                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5061                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5062                    if (versionedPackages == null) {
5063                        versionedPackages = new ArrayList<>();
5064                    }
5065                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5066                }
5067            }
5068        }
5069
5070        return versionedPackages;
5071    }
5072
5073    @Override
5074    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5075        if (!sUserManager.exists(userId)) return null;
5076        final int callingUid = Binder.getCallingUid();
5077        flags = updateFlagsForComponent(flags, userId, component);
5078        enforceCrossUserPermission(callingUid, userId,
5079                false /* requireFullPermission */, false /* checkShell */, "get service info");
5080        synchronized (mPackages) {
5081            PackageParser.Service s = mServices.mServices.get(component);
5082            if (DEBUG_PACKAGE_INFO) Log.v(
5083                TAG, "getServiceInfo " + component + ": " + s);
5084            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5085                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5086                if (ps == null) return null;
5087                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5088                    return null;
5089                }
5090                return PackageParser.generateServiceInfo(
5091                        s, flags, ps.readUserState(userId), userId);
5092            }
5093        }
5094        return null;
5095    }
5096
5097    @Override
5098    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5099        if (!sUserManager.exists(userId)) return null;
5100        final int callingUid = Binder.getCallingUid();
5101        flags = updateFlagsForComponent(flags, userId, component);
5102        enforceCrossUserPermission(callingUid, userId,
5103                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5104        synchronized (mPackages) {
5105            PackageParser.Provider p = mProviders.mProviders.get(component);
5106            if (DEBUG_PACKAGE_INFO) Log.v(
5107                TAG, "getProviderInfo " + component + ": " + p);
5108            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5109                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5110                if (ps == null) return null;
5111                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5112                    return null;
5113                }
5114                return PackageParser.generateProviderInfo(
5115                        p, flags, ps.readUserState(userId), userId);
5116            }
5117        }
5118        return null;
5119    }
5120
5121    @Override
5122    public String[] getSystemSharedLibraryNames() {
5123        // allow instant applications
5124        synchronized (mPackages) {
5125            Set<String> libs = null;
5126            final int libCount = mSharedLibraries.size();
5127            for (int i = 0; i < libCount; i++) {
5128                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5129                if (versionedLib == null) {
5130                    continue;
5131                }
5132                final int versionCount = versionedLib.size();
5133                for (int j = 0; j < versionCount; j++) {
5134                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5135                    if (!libEntry.info.isStatic()) {
5136                        if (libs == null) {
5137                            libs = new ArraySet<>();
5138                        }
5139                        libs.add(libEntry.info.getName());
5140                        break;
5141                    }
5142                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5143                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5144                            UserHandle.getUserId(Binder.getCallingUid()),
5145                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5146                        if (libs == null) {
5147                            libs = new ArraySet<>();
5148                        }
5149                        libs.add(libEntry.info.getName());
5150                        break;
5151                    }
5152                }
5153            }
5154
5155            if (libs != null) {
5156                String[] libsArray = new String[libs.size()];
5157                libs.toArray(libsArray);
5158                return libsArray;
5159            }
5160
5161            return null;
5162        }
5163    }
5164
5165    @Override
5166    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5167        // allow instant applications
5168        synchronized (mPackages) {
5169            return mServicesSystemSharedLibraryPackageName;
5170        }
5171    }
5172
5173    @Override
5174    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5175        // allow instant applications
5176        synchronized (mPackages) {
5177            return mSharedSystemSharedLibraryPackageName;
5178        }
5179    }
5180
5181    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5182        for (int i = userList.length - 1; i >= 0; --i) {
5183            final int userId = userList[i];
5184            // don't add instant app to the list of updates
5185            if (pkgSetting.getInstantApp(userId)) {
5186                continue;
5187            }
5188            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5189            if (changedPackages == null) {
5190                changedPackages = new SparseArray<>();
5191                mChangedPackages.put(userId, changedPackages);
5192            }
5193            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5194            if (sequenceNumbers == null) {
5195                sequenceNumbers = new HashMap<>();
5196                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5197            }
5198            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5199            if (sequenceNumber != null) {
5200                changedPackages.remove(sequenceNumber);
5201            }
5202            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5203            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5204        }
5205        mChangedPackagesSequenceNumber++;
5206    }
5207
5208    @Override
5209    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5210        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5211            return null;
5212        }
5213        synchronized (mPackages) {
5214            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5215                return null;
5216            }
5217            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5218            if (changedPackages == null) {
5219                return null;
5220            }
5221            final List<String> packageNames =
5222                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5223            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5224                final String packageName = changedPackages.get(i);
5225                if (packageName != null) {
5226                    packageNames.add(packageName);
5227                }
5228            }
5229            return packageNames.isEmpty()
5230                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5231        }
5232    }
5233
5234    @Override
5235    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5236        // allow instant applications
5237        ArrayList<FeatureInfo> res;
5238        synchronized (mAvailableFeatures) {
5239            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5240            res.addAll(mAvailableFeatures.values());
5241        }
5242        final FeatureInfo fi = new FeatureInfo();
5243        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5244                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5245        res.add(fi);
5246
5247        return new ParceledListSlice<>(res);
5248    }
5249
5250    @Override
5251    public boolean hasSystemFeature(String name, int version) {
5252        // allow instant applications
5253        synchronized (mAvailableFeatures) {
5254            final FeatureInfo feat = mAvailableFeatures.get(name);
5255            if (feat == null) {
5256                return false;
5257            } else {
5258                return feat.version >= version;
5259            }
5260        }
5261    }
5262
5263    @Override
5264    public int checkPermission(String permName, String pkgName, int userId) {
5265        if (!sUserManager.exists(userId)) {
5266            return PackageManager.PERMISSION_DENIED;
5267        }
5268        final int callingUid = Binder.getCallingUid();
5269
5270        synchronized (mPackages) {
5271            final PackageParser.Package p = mPackages.get(pkgName);
5272            if (p != null && p.mExtras != null) {
5273                final PackageSetting ps = (PackageSetting) p.mExtras;
5274                if (filterAppAccessLPr(ps, callingUid, userId)) {
5275                    return PackageManager.PERMISSION_DENIED;
5276                }
5277                final boolean instantApp = ps.getInstantApp(userId);
5278                final PermissionsState permissionsState = ps.getPermissionsState();
5279                if (permissionsState.hasPermission(permName, userId)) {
5280                    if (instantApp) {
5281                        BasePermission bp = mSettings.mPermissions.get(permName);
5282                        if (bp != null && bp.isInstant()) {
5283                            return PackageManager.PERMISSION_GRANTED;
5284                        }
5285                    } else {
5286                        return PackageManager.PERMISSION_GRANTED;
5287                    }
5288                }
5289                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5290                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5291                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5292                    return PackageManager.PERMISSION_GRANTED;
5293                }
5294            }
5295        }
5296
5297        return PackageManager.PERMISSION_DENIED;
5298    }
5299
5300    @Override
5301    public int checkUidPermission(String permName, int uid) {
5302        final int callingUid = Binder.getCallingUid();
5303        final int callingUserId = UserHandle.getUserId(callingUid);
5304        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5305        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5306        final int userId = UserHandle.getUserId(uid);
5307        if (!sUserManager.exists(userId)) {
5308            return PackageManager.PERMISSION_DENIED;
5309        }
5310
5311        synchronized (mPackages) {
5312            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5313            if (obj != null) {
5314                if (obj instanceof SharedUserSetting) {
5315                    if (isCallerInstantApp) {
5316                        return PackageManager.PERMISSION_DENIED;
5317                    }
5318                } else if (obj instanceof PackageSetting) {
5319                    final PackageSetting ps = (PackageSetting) obj;
5320                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5321                        return PackageManager.PERMISSION_DENIED;
5322                    }
5323                }
5324                final SettingBase settingBase = (SettingBase) obj;
5325                final PermissionsState permissionsState = settingBase.getPermissionsState();
5326                if (permissionsState.hasPermission(permName, userId)) {
5327                    if (isUidInstantApp) {
5328                        BasePermission bp = mSettings.mPermissions.get(permName);
5329                        if (bp != null && bp.isInstant()) {
5330                            return PackageManager.PERMISSION_GRANTED;
5331                        }
5332                    } else {
5333                        return PackageManager.PERMISSION_GRANTED;
5334                    }
5335                }
5336                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5337                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5338                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5339                    return PackageManager.PERMISSION_GRANTED;
5340                }
5341            } else {
5342                ArraySet<String> perms = mSystemPermissions.get(uid);
5343                if (perms != null) {
5344                    if (perms.contains(permName)) {
5345                        return PackageManager.PERMISSION_GRANTED;
5346                    }
5347                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5348                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5349                        return PackageManager.PERMISSION_GRANTED;
5350                    }
5351                }
5352            }
5353        }
5354
5355        return PackageManager.PERMISSION_DENIED;
5356    }
5357
5358    @Override
5359    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5360        if (UserHandle.getCallingUserId() != userId) {
5361            mContext.enforceCallingPermission(
5362                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5363                    "isPermissionRevokedByPolicy for user " + userId);
5364        }
5365
5366        if (checkPermission(permission, packageName, userId)
5367                == PackageManager.PERMISSION_GRANTED) {
5368            return false;
5369        }
5370
5371        final int callingUid = Binder.getCallingUid();
5372        if (getInstantAppPackageName(callingUid) != null) {
5373            if (!isCallerSameApp(packageName, callingUid)) {
5374                return false;
5375            }
5376        } else {
5377            if (isInstantApp(packageName, userId)) {
5378                return false;
5379            }
5380        }
5381
5382        final long identity = Binder.clearCallingIdentity();
5383        try {
5384            final int flags = getPermissionFlags(permission, packageName, userId);
5385            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5386        } finally {
5387            Binder.restoreCallingIdentity(identity);
5388        }
5389    }
5390
5391    @Override
5392    public String getPermissionControllerPackageName() {
5393        synchronized (mPackages) {
5394            return mRequiredInstallerPackage;
5395        }
5396    }
5397
5398    /**
5399     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5400     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5401     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5402     * @param message the message to log on security exception
5403     */
5404    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5405            boolean checkShell, String message) {
5406        if (userId < 0) {
5407            throw new IllegalArgumentException("Invalid userId " + userId);
5408        }
5409        if (checkShell) {
5410            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5411        }
5412        if (userId == UserHandle.getUserId(callingUid)) return;
5413        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5414            if (requireFullPermission) {
5415                mContext.enforceCallingOrSelfPermission(
5416                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5417            } else {
5418                try {
5419                    mContext.enforceCallingOrSelfPermission(
5420                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5421                } catch (SecurityException se) {
5422                    mContext.enforceCallingOrSelfPermission(
5423                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5424                }
5425            }
5426        }
5427    }
5428
5429    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5430        if (callingUid == Process.SHELL_UID) {
5431            if (userHandle >= 0
5432                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5433                throw new SecurityException("Shell does not have permission to access user "
5434                        + userHandle);
5435            } else if (userHandle < 0) {
5436                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5437                        + Debug.getCallers(3));
5438            }
5439        }
5440    }
5441
5442    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5443        int size = 0;
5444        for (BasePermission perm : mSettings.mPermissions.values()) {
5445            size += tree.calculateFootprint(perm);
5446        }
5447        return size;
5448    }
5449
5450    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5451        // We calculate the max size of permissions defined by this uid and throw
5452        // if that plus the size of 'info' would exceed our stated maximum.
5453        if (tree.getUid() != Process.SYSTEM_UID) {
5454            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5455            if (curTreeSize + info.calculateFootprint() > MAX_PERMISSION_TREE_FOOTPRINT) {
5456                throw new SecurityException("Permission tree size cap exceeded");
5457            }
5458        }
5459    }
5460
5461    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5462        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5463            throw new SecurityException("Instant apps can't add permissions");
5464        }
5465        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5466            throw new SecurityException("Label must be specified in permission");
5467        }
5468        BasePermission tree = BasePermission.enforcePermissionTreeLP(
5469                mSettings.mPermissionTrees, info.name, Binder.getCallingUid());
5470        BasePermission bp = mSettings.mPermissions.get(info.name);
5471        boolean added = bp == null;
5472        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5473        if (added) {
5474            enforcePermissionCapLocked(info, tree);
5475            bp = new BasePermission(info.name, tree.getSourcePackageName(),
5476                    BasePermission.TYPE_DYNAMIC);
5477        } else if (bp.isDynamic()) {
5478            throw new SecurityException(
5479                    "Not allowed to modify non-dynamic permission "
5480                    + info.name);
5481        }
5482        final boolean changed = bp.addToTree(fixedLevel, info, tree);
5483        if (added) {
5484            mSettings.mPermissions.put(info.name, bp);
5485        }
5486        if (changed) {
5487            if (!async) {
5488                mSettings.writeLPr();
5489            } else {
5490                scheduleWriteSettingsLocked();
5491            }
5492        }
5493        return added;
5494    }
5495
5496    @Override
5497    public boolean addPermission(PermissionInfo info) {
5498        synchronized (mPackages) {
5499            return addPermissionLocked(info, false);
5500        }
5501    }
5502
5503    @Override
5504    public boolean addPermissionAsync(PermissionInfo info) {
5505        synchronized (mPackages) {
5506            return addPermissionLocked(info, true);
5507        }
5508    }
5509
5510    @Override
5511    public void removePermission(String name) {
5512        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5513            throw new SecurityException("Instant applications don't have access to this method");
5514        }
5515        synchronized (mPackages) {
5516            BasePermission.enforcePermissionTreeLP(
5517                    mSettings.mPermissionTrees, name, Binder.getCallingUid());
5518            BasePermission bp = mSettings.mPermissions.get(name);
5519            if (bp != null) {
5520                if (bp.isDynamic()) {
5521                    throw new SecurityException(
5522                            "Not allowed to modify non-dynamic permission "
5523                            + name);
5524                }
5525                mSettings.mPermissions.remove(name);
5526                mSettings.writeLPr();
5527            }
5528        }
5529    }
5530
5531    @Override
5532    public void grantRuntimePermission(String packageName, String name, final int userId) {
5533        grantRuntimePermission(packageName, name, userId, false /*overridePolicy*/);
5534    }
5535
5536    private void grantRuntimePermission(String packageName, String name, final int userId,
5537            boolean overridePolicy) {
5538        if (!sUserManager.exists(userId)) {
5539            Log.e(TAG, "No such user:" + userId);
5540            return;
5541        }
5542        final int callingUid = Binder.getCallingUid();
5543
5544        mContext.enforceCallingOrSelfPermission(
5545                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5546                "grantRuntimePermission");
5547
5548        enforceCrossUserPermission(callingUid, userId,
5549                true /* requireFullPermission */, true /* checkShell */,
5550                "grantRuntimePermission");
5551
5552        final int uid;
5553        final PackageSetting ps;
5554
5555        synchronized (mPackages) {
5556            final PackageParser.Package pkg = mPackages.get(packageName);
5557            if (pkg == null) {
5558                throw new IllegalArgumentException("Unknown package: " + packageName);
5559            }
5560            final BasePermission bp = mSettings.mPermissions.get(name);
5561            if (bp == null) {
5562                throw new IllegalArgumentException("Unknown permission: " + name);
5563            }
5564            ps = (PackageSetting) pkg.mExtras;
5565            if (ps == null
5566                    || filterAppAccessLPr(ps, callingUid, userId)) {
5567                throw new IllegalArgumentException("Unknown package: " + packageName);
5568            }
5569
5570            bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg);
5571
5572            // If a permission review is required for legacy apps we represent
5573            // their permissions as always granted runtime ones since we need
5574            // to keep the review required permission flag per user while an
5575            // install permission's state is shared across all users.
5576            if (mPermissionReviewRequired
5577                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5578                    && bp.isRuntime()) {
5579                return;
5580            }
5581
5582            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5583
5584            final PermissionsState permissionsState = ps.getPermissionsState();
5585
5586            final int flags = permissionsState.getPermissionFlags(name, userId);
5587            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5588                throw new SecurityException("Cannot grant system fixed permission "
5589                        + name + " for package " + packageName);
5590            }
5591            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5592                throw new SecurityException("Cannot grant policy fixed permission "
5593                        + name + " for package " + packageName);
5594            }
5595
5596            if (bp.isDevelopment()) {
5597                // Development permissions must be handled specially, since they are not
5598                // normal runtime permissions.  For now they apply to all users.
5599                if (permissionsState.grantInstallPermission(bp) !=
5600                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5601                    scheduleWriteSettingsLocked();
5602                }
5603                return;
5604            }
5605
5606            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5607                throw new SecurityException("Cannot grant non-ephemeral permission"
5608                        + name + " for package " + packageName);
5609            }
5610
5611            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5612                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5613                return;
5614            }
5615
5616            final int result = permissionsState.grantRuntimePermission(bp, userId);
5617            switch (result) {
5618                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5619                    return;
5620                }
5621
5622                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5623                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5624                    mHandler.post(new Runnable() {
5625                        @Override
5626                        public void run() {
5627                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5628                        }
5629                    });
5630                }
5631                break;
5632            }
5633
5634            if (bp.isRuntime()) {
5635                logPermissionGranted(mContext, name, packageName);
5636            }
5637
5638            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5639
5640            // Not critical if that is lost - app has to request again.
5641            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5642        }
5643
5644        // Only need to do this if user is initialized. Otherwise it's a new user
5645        // and there are no processes running as the user yet and there's no need
5646        // to make an expensive call to remount processes for the changed permissions.
5647        if (READ_EXTERNAL_STORAGE.equals(name)
5648                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5649            final long token = Binder.clearCallingIdentity();
5650            try {
5651                if (sUserManager.isInitialized(userId)) {
5652                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5653                            StorageManagerInternal.class);
5654                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5655                }
5656            } finally {
5657                Binder.restoreCallingIdentity(token);
5658            }
5659        }
5660    }
5661
5662    @Override
5663    public void revokeRuntimePermission(String packageName, String name, int userId) {
5664        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5665    }
5666
5667    private void revokeRuntimePermission(String packageName, String name, int userId,
5668            boolean overridePolicy) {
5669        if (!sUserManager.exists(userId)) {
5670            Log.e(TAG, "No such user:" + userId);
5671            return;
5672        }
5673
5674        mContext.enforceCallingOrSelfPermission(
5675                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5676                "revokeRuntimePermission");
5677
5678        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5679                true /* requireFullPermission */, true /* checkShell */,
5680                "revokeRuntimePermission");
5681
5682        final int appId;
5683
5684        synchronized (mPackages) {
5685            final PackageParser.Package pkg = mPackages.get(packageName);
5686            if (pkg == null) {
5687                throw new IllegalArgumentException("Unknown package: " + packageName);
5688            }
5689            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5690            if (ps == null
5691                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5692                throw new IllegalArgumentException("Unknown package: " + packageName);
5693            }
5694            final BasePermission bp = mSettings.mPermissions.get(name);
5695            if (bp == null) {
5696                throw new IllegalArgumentException("Unknown permission: " + name);
5697            }
5698
5699            bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg);
5700
5701            // If a permission review is required for legacy apps we represent
5702            // their permissions as always granted runtime ones since we need
5703            // to keep the review required permission flag per user while an
5704            // install permission's state is shared across all users.
5705            if (mPermissionReviewRequired
5706                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5707                    && bp.isRuntime()) {
5708                return;
5709            }
5710
5711            final PermissionsState permissionsState = ps.getPermissionsState();
5712
5713            final int flags = permissionsState.getPermissionFlags(name, userId);
5714            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5715                throw new SecurityException("Cannot revoke system fixed permission "
5716                        + name + " for package " + packageName);
5717            }
5718            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5719                throw new SecurityException("Cannot revoke policy fixed permission "
5720                        + name + " for package " + packageName);
5721            }
5722
5723            if (bp.isDevelopment()) {
5724                // Development permissions must be handled specially, since they are not
5725                // normal runtime permissions.  For now they apply to all users.
5726                if (permissionsState.revokeInstallPermission(bp) !=
5727                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5728                    scheduleWriteSettingsLocked();
5729                }
5730                return;
5731            }
5732
5733            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5734                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5735                return;
5736            }
5737
5738            if (bp.isRuntime()) {
5739                logPermissionRevoked(mContext, name, packageName);
5740            }
5741
5742            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5743
5744            // Critical, after this call app should never have the permission.
5745            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5746
5747            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5748        }
5749
5750        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5751    }
5752
5753    /**
5754     * Get the first event id for the permission.
5755     *
5756     * <p>There are four events for each permission: <ul>
5757     *     <li>Request permission: first id + 0</li>
5758     *     <li>Grant permission: first id + 1</li>
5759     *     <li>Request for permission denied: first id + 2</li>
5760     *     <li>Revoke permission: first id + 3</li>
5761     * </ul></p>
5762     *
5763     * @param name name of the permission
5764     *
5765     * @return The first event id for the permission
5766     */
5767    private static int getBaseEventId(@NonNull String name) {
5768        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5769
5770        if (eventIdIndex == -1) {
5771            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5772                    || Build.IS_USER) {
5773                Log.i(TAG, "Unknown permission " + name);
5774
5775                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5776            } else {
5777                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5778                //
5779                // Also update
5780                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5781                // - metrics_constants.proto
5782                throw new IllegalStateException("Unknown permission " + name);
5783            }
5784        }
5785
5786        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5787    }
5788
5789    /**
5790     * Log that a permission was revoked.
5791     *
5792     * @param context Context of the caller
5793     * @param name name of the permission
5794     * @param packageName package permission if for
5795     */
5796    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5797            @NonNull String packageName) {
5798        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5799    }
5800
5801    /**
5802     * Log that a permission request was granted.
5803     *
5804     * @param context Context of the caller
5805     * @param name name of the permission
5806     * @param packageName package permission if for
5807     */
5808    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5809            @NonNull String packageName) {
5810        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5811    }
5812
5813    @Override
5814    public void resetRuntimePermissions() {
5815        mContext.enforceCallingOrSelfPermission(
5816                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5817                "revokeRuntimePermission");
5818
5819        int callingUid = Binder.getCallingUid();
5820        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5821            mContext.enforceCallingOrSelfPermission(
5822                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5823                    "resetRuntimePermissions");
5824        }
5825
5826        synchronized (mPackages) {
5827            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5828            for (int userId : UserManagerService.getInstance().getUserIds()) {
5829                final int packageCount = mPackages.size();
5830                for (int i = 0; i < packageCount; i++) {
5831                    PackageParser.Package pkg = mPackages.valueAt(i);
5832                    if (!(pkg.mExtras instanceof PackageSetting)) {
5833                        continue;
5834                    }
5835                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5836                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5837                }
5838            }
5839        }
5840    }
5841
5842    @Override
5843    public int getPermissionFlags(String name, String packageName, int userId) {
5844        if (!sUserManager.exists(userId)) {
5845            return 0;
5846        }
5847
5848        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5849
5850        final int callingUid = Binder.getCallingUid();
5851        enforceCrossUserPermission(callingUid, userId,
5852                true /* requireFullPermission */, false /* checkShell */,
5853                "getPermissionFlags");
5854
5855        synchronized (mPackages) {
5856            final PackageParser.Package pkg = mPackages.get(packageName);
5857            if (pkg == null) {
5858                return 0;
5859            }
5860            final BasePermission bp = mSettings.mPermissions.get(name);
5861            if (bp == null) {
5862                return 0;
5863            }
5864            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5865            if (ps == null
5866                    || filterAppAccessLPr(ps, callingUid, userId)) {
5867                return 0;
5868            }
5869            PermissionsState permissionsState = ps.getPermissionsState();
5870            return permissionsState.getPermissionFlags(name, userId);
5871        }
5872    }
5873
5874    @Override
5875    public void updatePermissionFlags(String name, String packageName, int flagMask,
5876            int flagValues, int userId) {
5877        if (!sUserManager.exists(userId)) {
5878            return;
5879        }
5880
5881        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5882
5883        final int callingUid = Binder.getCallingUid();
5884        enforceCrossUserPermission(callingUid, userId,
5885                true /* requireFullPermission */, true /* checkShell */,
5886                "updatePermissionFlags");
5887
5888        // Only the system can change these flags and nothing else.
5889        if (getCallingUid() != Process.SYSTEM_UID) {
5890            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5891            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5892            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5893            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5894            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5895        }
5896
5897        synchronized (mPackages) {
5898            final PackageParser.Package pkg = mPackages.get(packageName);
5899            if (pkg == null) {
5900                throw new IllegalArgumentException("Unknown package: " + packageName);
5901            }
5902            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5903            if (ps == null
5904                    || filterAppAccessLPr(ps, callingUid, userId)) {
5905                throw new IllegalArgumentException("Unknown package: " + packageName);
5906            }
5907
5908            final BasePermission bp = mSettings.mPermissions.get(name);
5909            if (bp == null) {
5910                throw new IllegalArgumentException("Unknown permission: " + name);
5911            }
5912
5913            PermissionsState permissionsState = ps.getPermissionsState();
5914
5915            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5916
5917            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5918                // Install and runtime permissions are stored in different places,
5919                // so figure out what permission changed and persist the change.
5920                if (permissionsState.getInstallPermissionState(name) != null) {
5921                    scheduleWriteSettingsLocked();
5922                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5923                        || hadState) {
5924                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5925                }
5926            }
5927        }
5928    }
5929
5930    /**
5931     * Update the permission flags for all packages and runtime permissions of a user in order
5932     * to allow device or profile owner to remove POLICY_FIXED.
5933     */
5934    @Override
5935    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5936        if (!sUserManager.exists(userId)) {
5937            return;
5938        }
5939
5940        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5941
5942        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5943                true /* requireFullPermission */, true /* checkShell */,
5944                "updatePermissionFlagsForAllApps");
5945
5946        // Only the system can change system fixed flags.
5947        if (getCallingUid() != Process.SYSTEM_UID) {
5948            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5949            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5950        }
5951
5952        synchronized (mPackages) {
5953            boolean changed = false;
5954            final int packageCount = mPackages.size();
5955            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5956                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5957                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5958                if (ps == null) {
5959                    continue;
5960                }
5961                PermissionsState permissionsState = ps.getPermissionsState();
5962                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5963                        userId, flagMask, flagValues);
5964            }
5965            if (changed) {
5966                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5967            }
5968        }
5969    }
5970
5971    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5972        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5973                != PackageManager.PERMISSION_GRANTED
5974            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5975                != PackageManager.PERMISSION_GRANTED) {
5976            throw new SecurityException(message + " requires "
5977                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5978                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5979        }
5980    }
5981
5982    @Override
5983    public boolean shouldShowRequestPermissionRationale(String permissionName,
5984            String packageName, int userId) {
5985        if (UserHandle.getCallingUserId() != userId) {
5986            mContext.enforceCallingPermission(
5987                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5988                    "canShowRequestPermissionRationale for user " + userId);
5989        }
5990
5991        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5992        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5993            return false;
5994        }
5995
5996        if (checkPermission(permissionName, packageName, userId)
5997                == PackageManager.PERMISSION_GRANTED) {
5998            return false;
5999        }
6000
6001        final int flags;
6002
6003        final long identity = Binder.clearCallingIdentity();
6004        try {
6005            flags = getPermissionFlags(permissionName,
6006                    packageName, userId);
6007        } finally {
6008            Binder.restoreCallingIdentity(identity);
6009        }
6010
6011        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6012                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6013                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6014
6015        if ((flags & fixedFlags) != 0) {
6016            return false;
6017        }
6018
6019        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6020    }
6021
6022    @Override
6023    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6024        mContext.enforceCallingOrSelfPermission(
6025                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6026                "addOnPermissionsChangeListener");
6027
6028        synchronized (mPackages) {
6029            mOnPermissionChangeListeners.addListenerLocked(listener);
6030        }
6031    }
6032
6033    @Override
6034    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6035        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6036            throw new SecurityException("Instant applications don't have access to this method");
6037        }
6038        synchronized (mPackages) {
6039            mOnPermissionChangeListeners.removeListenerLocked(listener);
6040        }
6041    }
6042
6043    @Override
6044    public boolean isProtectedBroadcast(String actionName) {
6045        // allow instant applications
6046        synchronized (mProtectedBroadcasts) {
6047            if (mProtectedBroadcasts.contains(actionName)) {
6048                return true;
6049            } else if (actionName != null) {
6050                // TODO: remove these terrible hacks
6051                if (actionName.startsWith("android.net.netmon.lingerExpired")
6052                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6053                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6054                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6055                    return true;
6056                }
6057            }
6058        }
6059        return false;
6060    }
6061
6062    @Override
6063    public int checkSignatures(String pkg1, String pkg2) {
6064        synchronized (mPackages) {
6065            final PackageParser.Package p1 = mPackages.get(pkg1);
6066            final PackageParser.Package p2 = mPackages.get(pkg2);
6067            if (p1 == null || p1.mExtras == null
6068                    || p2 == null || p2.mExtras == null) {
6069                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6070            }
6071            final int callingUid = Binder.getCallingUid();
6072            final int callingUserId = UserHandle.getUserId(callingUid);
6073            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6074            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6075            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6076                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6077                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6078            }
6079            return compareSignatures(p1.mSignatures, p2.mSignatures);
6080        }
6081    }
6082
6083    @Override
6084    public int checkUidSignatures(int uid1, int uid2) {
6085        final int callingUid = Binder.getCallingUid();
6086        final int callingUserId = UserHandle.getUserId(callingUid);
6087        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6088        // Map to base uids.
6089        uid1 = UserHandle.getAppId(uid1);
6090        uid2 = UserHandle.getAppId(uid2);
6091        // reader
6092        synchronized (mPackages) {
6093            Signature[] s1;
6094            Signature[] s2;
6095            Object obj = mSettings.getUserIdLPr(uid1);
6096            if (obj != null) {
6097                if (obj instanceof SharedUserSetting) {
6098                    if (isCallerInstantApp) {
6099                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6100                    }
6101                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6102                } else if (obj instanceof PackageSetting) {
6103                    final PackageSetting ps = (PackageSetting) obj;
6104                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6105                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6106                    }
6107                    s1 = ps.signatures.mSignatures;
6108                } else {
6109                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6110                }
6111            } else {
6112                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6113            }
6114            obj = mSettings.getUserIdLPr(uid2);
6115            if (obj != null) {
6116                if (obj instanceof SharedUserSetting) {
6117                    if (isCallerInstantApp) {
6118                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6119                    }
6120                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6121                } else if (obj instanceof PackageSetting) {
6122                    final PackageSetting ps = (PackageSetting) obj;
6123                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6124                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6125                    }
6126                    s2 = ps.signatures.mSignatures;
6127                } else {
6128                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6129                }
6130            } else {
6131                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6132            }
6133            return compareSignatures(s1, s2);
6134        }
6135    }
6136
6137    /**
6138     * This method should typically only be used when granting or revoking
6139     * permissions, since the app may immediately restart after this call.
6140     * <p>
6141     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6142     * guard your work against the app being relaunched.
6143     */
6144    private void killUid(int appId, int userId, String reason) {
6145        final long identity = Binder.clearCallingIdentity();
6146        try {
6147            IActivityManager am = ActivityManager.getService();
6148            if (am != null) {
6149                try {
6150                    am.killUid(appId, userId, reason);
6151                } catch (RemoteException e) {
6152                    /* ignore - same process */
6153                }
6154            }
6155        } finally {
6156            Binder.restoreCallingIdentity(identity);
6157        }
6158    }
6159
6160    /**
6161     * Compares two sets of signatures. Returns:
6162     * <br />
6163     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6164     * <br />
6165     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6166     * <br />
6167     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6168     * <br />
6169     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6170     * <br />
6171     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6172     */
6173    public static int compareSignatures(Signature[] s1, Signature[] s2) {
6174        if (s1 == null) {
6175            return s2 == null
6176                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6177                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6178        }
6179
6180        if (s2 == null) {
6181            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6182        }
6183
6184        if (s1.length != s2.length) {
6185            return PackageManager.SIGNATURE_NO_MATCH;
6186        }
6187
6188        // Since both signature sets are of size 1, we can compare without HashSets.
6189        if (s1.length == 1) {
6190            return s1[0].equals(s2[0]) ?
6191                    PackageManager.SIGNATURE_MATCH :
6192                    PackageManager.SIGNATURE_NO_MATCH;
6193        }
6194
6195        ArraySet<Signature> set1 = new ArraySet<Signature>();
6196        for (Signature sig : s1) {
6197            set1.add(sig);
6198        }
6199        ArraySet<Signature> set2 = new ArraySet<Signature>();
6200        for (Signature sig : s2) {
6201            set2.add(sig);
6202        }
6203        // Make sure s2 contains all signatures in s1.
6204        if (set1.equals(set2)) {
6205            return PackageManager.SIGNATURE_MATCH;
6206        }
6207        return PackageManager.SIGNATURE_NO_MATCH;
6208    }
6209
6210    /**
6211     * If the database version for this type of package (internal storage or
6212     * external storage) is less than the version where package signatures
6213     * were updated, return true.
6214     */
6215    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6216        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6217        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6218    }
6219
6220    /**
6221     * Used for backward compatibility to make sure any packages with
6222     * certificate chains get upgraded to the new style. {@code existingSigs}
6223     * will be in the old format (since they were stored on disk from before the
6224     * system upgrade) and {@code scannedSigs} will be in the newer format.
6225     */
6226    private int compareSignaturesCompat(PackageSignatures existingSigs,
6227            PackageParser.Package scannedPkg) {
6228        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6229            return PackageManager.SIGNATURE_NO_MATCH;
6230        }
6231
6232        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6233        for (Signature sig : existingSigs.mSignatures) {
6234            existingSet.add(sig);
6235        }
6236        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6237        for (Signature sig : scannedPkg.mSignatures) {
6238            try {
6239                Signature[] chainSignatures = sig.getChainSignatures();
6240                for (Signature chainSig : chainSignatures) {
6241                    scannedCompatSet.add(chainSig);
6242                }
6243            } catch (CertificateEncodingException e) {
6244                scannedCompatSet.add(sig);
6245            }
6246        }
6247        /*
6248         * Make sure the expanded scanned set contains all signatures in the
6249         * existing one.
6250         */
6251        if (scannedCompatSet.equals(existingSet)) {
6252            // Migrate the old signatures to the new scheme.
6253            existingSigs.assignSignatures(scannedPkg.mSignatures);
6254            // The new KeySets will be re-added later in the scanning process.
6255            synchronized (mPackages) {
6256                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6257            }
6258            return PackageManager.SIGNATURE_MATCH;
6259        }
6260        return PackageManager.SIGNATURE_NO_MATCH;
6261    }
6262
6263    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6264        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6265        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6266    }
6267
6268    private int compareSignaturesRecover(PackageSignatures existingSigs,
6269            PackageParser.Package scannedPkg) {
6270        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6271            return PackageManager.SIGNATURE_NO_MATCH;
6272        }
6273
6274        String msg = null;
6275        try {
6276            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6277                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6278                        + scannedPkg.packageName);
6279                return PackageManager.SIGNATURE_MATCH;
6280            }
6281        } catch (CertificateException e) {
6282            msg = e.getMessage();
6283        }
6284
6285        logCriticalInfo(Log.INFO,
6286                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6287        return PackageManager.SIGNATURE_NO_MATCH;
6288    }
6289
6290    @Override
6291    public List<String> getAllPackages() {
6292        final int callingUid = Binder.getCallingUid();
6293        final int callingUserId = UserHandle.getUserId(callingUid);
6294        synchronized (mPackages) {
6295            if (canViewInstantApps(callingUid, callingUserId)) {
6296                return new ArrayList<String>(mPackages.keySet());
6297            }
6298            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6299            final List<String> result = new ArrayList<>();
6300            if (instantAppPkgName != null) {
6301                // caller is an instant application; filter unexposed applications
6302                for (PackageParser.Package pkg : mPackages.values()) {
6303                    if (!pkg.visibleToInstantApps) {
6304                        continue;
6305                    }
6306                    result.add(pkg.packageName);
6307                }
6308            } else {
6309                // caller is a normal application; filter instant applications
6310                for (PackageParser.Package pkg : mPackages.values()) {
6311                    final PackageSetting ps =
6312                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6313                    if (ps != null
6314                            && ps.getInstantApp(callingUserId)
6315                            && !mInstantAppRegistry.isInstantAccessGranted(
6316                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6317                        continue;
6318                    }
6319                    result.add(pkg.packageName);
6320                }
6321            }
6322            return result;
6323        }
6324    }
6325
6326    @Override
6327    public String[] getPackagesForUid(int uid) {
6328        final int callingUid = Binder.getCallingUid();
6329        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6330        final int userId = UserHandle.getUserId(uid);
6331        uid = UserHandle.getAppId(uid);
6332        // reader
6333        synchronized (mPackages) {
6334            Object obj = mSettings.getUserIdLPr(uid);
6335            if (obj instanceof SharedUserSetting) {
6336                if (isCallerInstantApp) {
6337                    return null;
6338                }
6339                final SharedUserSetting sus = (SharedUserSetting) obj;
6340                final int N = sus.packages.size();
6341                String[] res = new String[N];
6342                final Iterator<PackageSetting> it = sus.packages.iterator();
6343                int i = 0;
6344                while (it.hasNext()) {
6345                    PackageSetting ps = it.next();
6346                    if (ps.getInstalled(userId)) {
6347                        res[i++] = ps.name;
6348                    } else {
6349                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6350                    }
6351                }
6352                return res;
6353            } else if (obj instanceof PackageSetting) {
6354                final PackageSetting ps = (PackageSetting) obj;
6355                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6356                    return new String[]{ps.name};
6357                }
6358            }
6359        }
6360        return null;
6361    }
6362
6363    @Override
6364    public String getNameForUid(int uid) {
6365        final int callingUid = Binder.getCallingUid();
6366        if (getInstantAppPackageName(callingUid) != null) {
6367            return null;
6368        }
6369        synchronized (mPackages) {
6370            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6371            if (obj instanceof SharedUserSetting) {
6372                final SharedUserSetting sus = (SharedUserSetting) obj;
6373                return sus.name + ":" + sus.userId;
6374            } else if (obj instanceof PackageSetting) {
6375                final PackageSetting ps = (PackageSetting) obj;
6376                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6377                    return null;
6378                }
6379                return ps.name;
6380            }
6381            return null;
6382        }
6383    }
6384
6385    @Override
6386    public String[] getNamesForUids(int[] uids) {
6387        if (uids == null || uids.length == 0) {
6388            return null;
6389        }
6390        final int callingUid = Binder.getCallingUid();
6391        if (getInstantAppPackageName(callingUid) != null) {
6392            return null;
6393        }
6394        final String[] names = new String[uids.length];
6395        synchronized (mPackages) {
6396            for (int i = uids.length - 1; i >= 0; i--) {
6397                final int uid = uids[i];
6398                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6399                if (obj instanceof SharedUserSetting) {
6400                    final SharedUserSetting sus = (SharedUserSetting) obj;
6401                    names[i] = "shared:" + sus.name;
6402                } else if (obj instanceof PackageSetting) {
6403                    final PackageSetting ps = (PackageSetting) obj;
6404                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6405                        names[i] = null;
6406                    } else {
6407                        names[i] = ps.name;
6408                    }
6409                } else {
6410                    names[i] = null;
6411                }
6412            }
6413        }
6414        return names;
6415    }
6416
6417    @Override
6418    public int getUidForSharedUser(String sharedUserName) {
6419        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6420            return -1;
6421        }
6422        if (sharedUserName == null) {
6423            return -1;
6424        }
6425        // reader
6426        synchronized (mPackages) {
6427            SharedUserSetting suid;
6428            try {
6429                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6430                if (suid != null) {
6431                    return suid.userId;
6432                }
6433            } catch (PackageManagerException ignore) {
6434                // can't happen, but, still need to catch it
6435            }
6436            return -1;
6437        }
6438    }
6439
6440    @Override
6441    public int getFlagsForUid(int uid) {
6442        final int callingUid = Binder.getCallingUid();
6443        if (getInstantAppPackageName(callingUid) != null) {
6444            return 0;
6445        }
6446        synchronized (mPackages) {
6447            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6448            if (obj instanceof SharedUserSetting) {
6449                final SharedUserSetting sus = (SharedUserSetting) obj;
6450                return sus.pkgFlags;
6451            } else if (obj instanceof PackageSetting) {
6452                final PackageSetting ps = (PackageSetting) obj;
6453                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6454                    return 0;
6455                }
6456                return ps.pkgFlags;
6457            }
6458        }
6459        return 0;
6460    }
6461
6462    @Override
6463    public int getPrivateFlagsForUid(int uid) {
6464        final int callingUid = Binder.getCallingUid();
6465        if (getInstantAppPackageName(callingUid) != null) {
6466            return 0;
6467        }
6468        synchronized (mPackages) {
6469            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6470            if (obj instanceof SharedUserSetting) {
6471                final SharedUserSetting sus = (SharedUserSetting) obj;
6472                return sus.pkgPrivateFlags;
6473            } else if (obj instanceof PackageSetting) {
6474                final PackageSetting ps = (PackageSetting) obj;
6475                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6476                    return 0;
6477                }
6478                return ps.pkgPrivateFlags;
6479            }
6480        }
6481        return 0;
6482    }
6483
6484    @Override
6485    public boolean isUidPrivileged(int uid) {
6486        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6487            return false;
6488        }
6489        uid = UserHandle.getAppId(uid);
6490        // reader
6491        synchronized (mPackages) {
6492            Object obj = mSettings.getUserIdLPr(uid);
6493            if (obj instanceof SharedUserSetting) {
6494                final SharedUserSetting sus = (SharedUserSetting) obj;
6495                final Iterator<PackageSetting> it = sus.packages.iterator();
6496                while (it.hasNext()) {
6497                    if (it.next().isPrivileged()) {
6498                        return true;
6499                    }
6500                }
6501            } else if (obj instanceof PackageSetting) {
6502                final PackageSetting ps = (PackageSetting) obj;
6503                return ps.isPrivileged();
6504            }
6505        }
6506        return false;
6507    }
6508
6509    @Override
6510    public String[] getAppOpPermissionPackages(String permissionName) {
6511        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6512            return null;
6513        }
6514        synchronized (mPackages) {
6515            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6516            if (pkgs == null) {
6517                return null;
6518            }
6519            return pkgs.toArray(new String[pkgs.size()]);
6520        }
6521    }
6522
6523    @Override
6524    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6525            int flags, int userId) {
6526        return resolveIntentInternal(
6527                intent, resolvedType, flags, userId, false /*resolveForStart*/);
6528    }
6529
6530    /**
6531     * Normally instant apps can only be resolved when they're visible to the caller.
6532     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
6533     * since we need to allow the system to start any installed application.
6534     */
6535    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6536            int flags, int userId, boolean resolveForStart) {
6537        try {
6538            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6539
6540            if (!sUserManager.exists(userId)) return null;
6541            final int callingUid = Binder.getCallingUid();
6542            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6543            enforceCrossUserPermission(callingUid, userId,
6544                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6545
6546            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6547            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6548                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6549            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6550
6551            final ResolveInfo bestChoice =
6552                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6553            return bestChoice;
6554        } finally {
6555            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6556        }
6557    }
6558
6559    @Override
6560    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6561        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6562            throw new SecurityException(
6563                    "findPersistentPreferredActivity can only be run by the system");
6564        }
6565        if (!sUserManager.exists(userId)) {
6566            return null;
6567        }
6568        final int callingUid = Binder.getCallingUid();
6569        intent = updateIntentForResolve(intent);
6570        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6571        final int flags = updateFlagsForResolve(
6572                0, userId, intent, callingUid, false /*includeInstantApps*/);
6573        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6574                userId);
6575        synchronized (mPackages) {
6576            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6577                    userId);
6578        }
6579    }
6580
6581    @Override
6582    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6583            IntentFilter filter, int match, ComponentName activity) {
6584        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6585            return;
6586        }
6587        final int userId = UserHandle.getCallingUserId();
6588        if (DEBUG_PREFERRED) {
6589            Log.v(TAG, "setLastChosenActivity intent=" + intent
6590                + " resolvedType=" + resolvedType
6591                + " flags=" + flags
6592                + " filter=" + filter
6593                + " match=" + match
6594                + " activity=" + activity);
6595            filter.dump(new PrintStreamPrinter(System.out), "    ");
6596        }
6597        intent.setComponent(null);
6598        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6599                userId);
6600        // Find any earlier preferred or last chosen entries and nuke them
6601        findPreferredActivity(intent, resolvedType,
6602                flags, query, 0, false, true, false, userId);
6603        // Add the new activity as the last chosen for this filter
6604        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6605                "Setting last chosen");
6606    }
6607
6608    @Override
6609    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6610        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6611            return null;
6612        }
6613        final int userId = UserHandle.getCallingUserId();
6614        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6615        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6616                userId);
6617        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6618                false, false, false, userId);
6619    }
6620
6621    /**
6622     * Returns whether or not instant apps have been disabled remotely.
6623     */
6624    private boolean isEphemeralDisabled() {
6625        return mEphemeralAppsDisabled;
6626    }
6627
6628    private boolean isInstantAppAllowed(
6629            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6630            boolean skipPackageCheck) {
6631        if (mInstantAppResolverConnection == null) {
6632            return false;
6633        }
6634        if (mInstantAppInstallerActivity == null) {
6635            return false;
6636        }
6637        if (intent.getComponent() != null) {
6638            return false;
6639        }
6640        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6641            return false;
6642        }
6643        if (!skipPackageCheck && intent.getPackage() != null) {
6644            return false;
6645        }
6646        final boolean isWebUri = hasWebURI(intent);
6647        if (!isWebUri || intent.getData().getHost() == null) {
6648            return false;
6649        }
6650        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6651        // Or if there's already an ephemeral app installed that handles the action
6652        synchronized (mPackages) {
6653            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6654            for (int n = 0; n < count; n++) {
6655                final ResolveInfo info = resolvedActivities.get(n);
6656                final String packageName = info.activityInfo.packageName;
6657                final PackageSetting ps = mSettings.mPackages.get(packageName);
6658                if (ps != null) {
6659                    // only check domain verification status if the app is not a browser
6660                    if (!info.handleAllWebDataURI) {
6661                        // Try to get the status from User settings first
6662                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6663                        final int status = (int) (packedStatus >> 32);
6664                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6665                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6666                            if (DEBUG_EPHEMERAL) {
6667                                Slog.v(TAG, "DENY instant app;"
6668                                    + " pkg: " + packageName + ", status: " + status);
6669                            }
6670                            return false;
6671                        }
6672                    }
6673                    if (ps.getInstantApp(userId)) {
6674                        if (DEBUG_EPHEMERAL) {
6675                            Slog.v(TAG, "DENY instant app installed;"
6676                                    + " pkg: " + packageName);
6677                        }
6678                        return false;
6679                    }
6680                }
6681            }
6682        }
6683        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6684        return true;
6685    }
6686
6687    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6688            Intent origIntent, String resolvedType, String callingPackage,
6689            Bundle verificationBundle, int userId) {
6690        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6691                new InstantAppRequest(responseObj, origIntent, resolvedType,
6692                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6693        mHandler.sendMessage(msg);
6694    }
6695
6696    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6697            int flags, List<ResolveInfo> query, int userId) {
6698        if (query != null) {
6699            final int N = query.size();
6700            if (N == 1) {
6701                return query.get(0);
6702            } else if (N > 1) {
6703                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6704                // If there is more than one activity with the same priority,
6705                // then let the user decide between them.
6706                ResolveInfo r0 = query.get(0);
6707                ResolveInfo r1 = query.get(1);
6708                if (DEBUG_INTENT_MATCHING || debug) {
6709                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6710                            + r1.activityInfo.name + "=" + r1.priority);
6711                }
6712                // If the first activity has a higher priority, or a different
6713                // default, then it is always desirable to pick it.
6714                if (r0.priority != r1.priority
6715                        || r0.preferredOrder != r1.preferredOrder
6716                        || r0.isDefault != r1.isDefault) {
6717                    return query.get(0);
6718                }
6719                // If we have saved a preference for a preferred activity for
6720                // this Intent, use that.
6721                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6722                        flags, query, r0.priority, true, false, debug, userId);
6723                if (ri != null) {
6724                    return ri;
6725                }
6726                // If we have an ephemeral app, use it
6727                for (int i = 0; i < N; i++) {
6728                    ri = query.get(i);
6729                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6730                        final String packageName = ri.activityInfo.packageName;
6731                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6732                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6733                        final int status = (int)(packedStatus >> 32);
6734                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6735                            return ri;
6736                        }
6737                    }
6738                }
6739                ri = new ResolveInfo(mResolveInfo);
6740                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6741                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6742                // If all of the options come from the same package, show the application's
6743                // label and icon instead of the generic resolver's.
6744                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6745                // and then throw away the ResolveInfo itself, meaning that the caller loses
6746                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6747                // a fallback for this case; we only set the target package's resources on
6748                // the ResolveInfo, not the ActivityInfo.
6749                final String intentPackage = intent.getPackage();
6750                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6751                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6752                    ri.resolvePackageName = intentPackage;
6753                    if (userNeedsBadging(userId)) {
6754                        ri.noResourceId = true;
6755                    } else {
6756                        ri.icon = appi.icon;
6757                    }
6758                    ri.iconResourceId = appi.icon;
6759                    ri.labelRes = appi.labelRes;
6760                }
6761                ri.activityInfo.applicationInfo = new ApplicationInfo(
6762                        ri.activityInfo.applicationInfo);
6763                if (userId != 0) {
6764                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6765                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6766                }
6767                // Make sure that the resolver is displayable in car mode
6768                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6769                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6770                return ri;
6771            }
6772        }
6773        return null;
6774    }
6775
6776    /**
6777     * Return true if the given list is not empty and all of its contents have
6778     * an activityInfo with the given package name.
6779     */
6780    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6781        if (ArrayUtils.isEmpty(list)) {
6782            return false;
6783        }
6784        for (int i = 0, N = list.size(); i < N; i++) {
6785            final ResolveInfo ri = list.get(i);
6786            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6787            if (ai == null || !packageName.equals(ai.packageName)) {
6788                return false;
6789            }
6790        }
6791        return true;
6792    }
6793
6794    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6795            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6796        final int N = query.size();
6797        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6798                .get(userId);
6799        // Get the list of persistent preferred activities that handle the intent
6800        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6801        List<PersistentPreferredActivity> pprefs = ppir != null
6802                ? ppir.queryIntent(intent, resolvedType,
6803                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6804                        userId)
6805                : null;
6806        if (pprefs != null && pprefs.size() > 0) {
6807            final int M = pprefs.size();
6808            for (int i=0; i<M; i++) {
6809                final PersistentPreferredActivity ppa = pprefs.get(i);
6810                if (DEBUG_PREFERRED || debug) {
6811                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6812                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6813                            + "\n  component=" + ppa.mComponent);
6814                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6815                }
6816                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6817                        flags | MATCH_DISABLED_COMPONENTS, userId);
6818                if (DEBUG_PREFERRED || debug) {
6819                    Slog.v(TAG, "Found persistent preferred activity:");
6820                    if (ai != null) {
6821                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6822                    } else {
6823                        Slog.v(TAG, "  null");
6824                    }
6825                }
6826                if (ai == null) {
6827                    // This previously registered persistent preferred activity
6828                    // component is no longer known. Ignore it and do NOT remove it.
6829                    continue;
6830                }
6831                for (int j=0; j<N; j++) {
6832                    final ResolveInfo ri = query.get(j);
6833                    if (!ri.activityInfo.applicationInfo.packageName
6834                            .equals(ai.applicationInfo.packageName)) {
6835                        continue;
6836                    }
6837                    if (!ri.activityInfo.name.equals(ai.name)) {
6838                        continue;
6839                    }
6840                    //  Found a persistent preference that can handle the intent.
6841                    if (DEBUG_PREFERRED || debug) {
6842                        Slog.v(TAG, "Returning persistent preferred activity: " +
6843                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6844                    }
6845                    return ri;
6846                }
6847            }
6848        }
6849        return null;
6850    }
6851
6852    // TODO: handle preferred activities missing while user has amnesia
6853    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6854            List<ResolveInfo> query, int priority, boolean always,
6855            boolean removeMatches, boolean debug, int userId) {
6856        if (!sUserManager.exists(userId)) return null;
6857        final int callingUid = Binder.getCallingUid();
6858        flags = updateFlagsForResolve(
6859                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6860        intent = updateIntentForResolve(intent);
6861        // writer
6862        synchronized (mPackages) {
6863            // Try to find a matching persistent preferred activity.
6864            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6865                    debug, userId);
6866
6867            // If a persistent preferred activity matched, use it.
6868            if (pri != null) {
6869                return pri;
6870            }
6871
6872            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6873            // Get the list of preferred activities that handle the intent
6874            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6875            List<PreferredActivity> prefs = pir != null
6876                    ? pir.queryIntent(intent, resolvedType,
6877                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6878                            userId)
6879                    : null;
6880            if (prefs != null && prefs.size() > 0) {
6881                boolean changed = false;
6882                try {
6883                    // First figure out how good the original match set is.
6884                    // We will only allow preferred activities that came
6885                    // from the same match quality.
6886                    int match = 0;
6887
6888                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6889
6890                    final int N = query.size();
6891                    for (int j=0; j<N; j++) {
6892                        final ResolveInfo ri = query.get(j);
6893                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6894                                + ": 0x" + Integer.toHexString(match));
6895                        if (ri.match > match) {
6896                            match = ri.match;
6897                        }
6898                    }
6899
6900                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6901                            + Integer.toHexString(match));
6902
6903                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6904                    final int M = prefs.size();
6905                    for (int i=0; i<M; i++) {
6906                        final PreferredActivity pa = prefs.get(i);
6907                        if (DEBUG_PREFERRED || debug) {
6908                            Slog.v(TAG, "Checking PreferredActivity ds="
6909                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6910                                    + "\n  component=" + pa.mPref.mComponent);
6911                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6912                        }
6913                        if (pa.mPref.mMatch != match) {
6914                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6915                                    + Integer.toHexString(pa.mPref.mMatch));
6916                            continue;
6917                        }
6918                        // If it's not an "always" type preferred activity and that's what we're
6919                        // looking for, skip it.
6920                        if (always && !pa.mPref.mAlways) {
6921                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6922                            continue;
6923                        }
6924                        final ActivityInfo ai = getActivityInfo(
6925                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6926                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6927                                userId);
6928                        if (DEBUG_PREFERRED || debug) {
6929                            Slog.v(TAG, "Found preferred activity:");
6930                            if (ai != null) {
6931                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6932                            } else {
6933                                Slog.v(TAG, "  null");
6934                            }
6935                        }
6936                        if (ai == null) {
6937                            // This previously registered preferred activity
6938                            // component is no longer known.  Most likely an update
6939                            // to the app was installed and in the new version this
6940                            // component no longer exists.  Clean it up by removing
6941                            // it from the preferred activities list, and skip it.
6942                            Slog.w(TAG, "Removing dangling preferred activity: "
6943                                    + pa.mPref.mComponent);
6944                            pir.removeFilter(pa);
6945                            changed = true;
6946                            continue;
6947                        }
6948                        for (int j=0; j<N; j++) {
6949                            final ResolveInfo ri = query.get(j);
6950                            if (!ri.activityInfo.applicationInfo.packageName
6951                                    .equals(ai.applicationInfo.packageName)) {
6952                                continue;
6953                            }
6954                            if (!ri.activityInfo.name.equals(ai.name)) {
6955                                continue;
6956                            }
6957
6958                            if (removeMatches) {
6959                                pir.removeFilter(pa);
6960                                changed = true;
6961                                if (DEBUG_PREFERRED) {
6962                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6963                                }
6964                                break;
6965                            }
6966
6967                            // Okay we found a previously set preferred or last chosen app.
6968                            // If the result set is different from when this
6969                            // was created, and is not a subset of the preferred set, we need to
6970                            // clear it and re-ask the user their preference, if we're looking for
6971                            // an "always" type entry.
6972                            if (always && !pa.mPref.sameSet(query)) {
6973                                if (pa.mPref.isSuperset(query)) {
6974                                    // some components of the set are no longer present in
6975                                    // the query, but the preferred activity can still be reused
6976                                    if (DEBUG_PREFERRED) {
6977                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6978                                                + " still valid as only non-preferred components"
6979                                                + " were removed for " + intent + " type "
6980                                                + resolvedType);
6981                                    }
6982                                    // remove obsolete components and re-add the up-to-date filter
6983                                    PreferredActivity freshPa = new PreferredActivity(pa,
6984                                            pa.mPref.mMatch,
6985                                            pa.mPref.discardObsoleteComponents(query),
6986                                            pa.mPref.mComponent,
6987                                            pa.mPref.mAlways);
6988                                    pir.removeFilter(pa);
6989                                    pir.addFilter(freshPa);
6990                                    changed = true;
6991                                } else {
6992                                    Slog.i(TAG,
6993                                            "Result set changed, dropping preferred activity for "
6994                                                    + intent + " type " + resolvedType);
6995                                    if (DEBUG_PREFERRED) {
6996                                        Slog.v(TAG, "Removing preferred activity since set changed "
6997                                                + pa.mPref.mComponent);
6998                                    }
6999                                    pir.removeFilter(pa);
7000                                    // Re-add the filter as a "last chosen" entry (!always)
7001                                    PreferredActivity lastChosen = new PreferredActivity(
7002                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7003                                    pir.addFilter(lastChosen);
7004                                    changed = true;
7005                                    return null;
7006                                }
7007                            }
7008
7009                            // Yay! Either the set matched or we're looking for the last chosen
7010                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7011                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7012                            return ri;
7013                        }
7014                    }
7015                } finally {
7016                    if (changed) {
7017                        if (DEBUG_PREFERRED) {
7018                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7019                        }
7020                        scheduleWritePackageRestrictionsLocked(userId);
7021                    }
7022                }
7023            }
7024        }
7025        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7026        return null;
7027    }
7028
7029    /*
7030     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7031     */
7032    @Override
7033    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7034            int targetUserId) {
7035        mContext.enforceCallingOrSelfPermission(
7036                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7037        List<CrossProfileIntentFilter> matches =
7038                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7039        if (matches != null) {
7040            int size = matches.size();
7041            for (int i = 0; i < size; i++) {
7042                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7043            }
7044        }
7045        if (hasWebURI(intent)) {
7046            // cross-profile app linking works only towards the parent.
7047            final int callingUid = Binder.getCallingUid();
7048            final UserInfo parent = getProfileParent(sourceUserId);
7049            synchronized(mPackages) {
7050                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7051                        false /*includeInstantApps*/);
7052                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7053                        intent, resolvedType, flags, sourceUserId, parent.id);
7054                return xpDomainInfo != null;
7055            }
7056        }
7057        return false;
7058    }
7059
7060    private UserInfo getProfileParent(int userId) {
7061        final long identity = Binder.clearCallingIdentity();
7062        try {
7063            return sUserManager.getProfileParent(userId);
7064        } finally {
7065            Binder.restoreCallingIdentity(identity);
7066        }
7067    }
7068
7069    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7070            String resolvedType, int userId) {
7071        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7072        if (resolver != null) {
7073            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7074        }
7075        return null;
7076    }
7077
7078    @Override
7079    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7080            String resolvedType, int flags, int userId) {
7081        try {
7082            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7083
7084            return new ParceledListSlice<>(
7085                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7086        } finally {
7087            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7088        }
7089    }
7090
7091    /**
7092     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7093     * instant, returns {@code null}.
7094     */
7095    private String getInstantAppPackageName(int callingUid) {
7096        synchronized (mPackages) {
7097            // If the caller is an isolated app use the owner's uid for the lookup.
7098            if (Process.isIsolated(callingUid)) {
7099                callingUid = mIsolatedOwners.get(callingUid);
7100            }
7101            final int appId = UserHandle.getAppId(callingUid);
7102            final Object obj = mSettings.getUserIdLPr(appId);
7103            if (obj instanceof PackageSetting) {
7104                final PackageSetting ps = (PackageSetting) obj;
7105                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7106                return isInstantApp ? ps.pkg.packageName : null;
7107            }
7108        }
7109        return null;
7110    }
7111
7112    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7113            String resolvedType, int flags, int userId) {
7114        return queryIntentActivitiesInternal(
7115                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7116                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7117    }
7118
7119    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7120            String resolvedType, int flags, int filterCallingUid, int userId,
7121            boolean resolveForStart, boolean allowDynamicSplits) {
7122        if (!sUserManager.exists(userId)) return Collections.emptyList();
7123        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7124        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7125                false /* requireFullPermission */, false /* checkShell */,
7126                "query intent activities");
7127        final String pkgName = intent.getPackage();
7128        ComponentName comp = intent.getComponent();
7129        if (comp == null) {
7130            if (intent.getSelector() != null) {
7131                intent = intent.getSelector();
7132                comp = intent.getComponent();
7133            }
7134        }
7135
7136        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7137                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7138        if (comp != null) {
7139            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7140            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7141            if (ai != null) {
7142                // When specifying an explicit component, we prevent the activity from being
7143                // used when either 1) the calling package is normal and the activity is within
7144                // an ephemeral application or 2) the calling package is ephemeral and the
7145                // activity is not visible to ephemeral applications.
7146                final boolean matchInstantApp =
7147                        (flags & PackageManager.MATCH_INSTANT) != 0;
7148                final boolean matchVisibleToInstantAppOnly =
7149                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7150                final boolean matchExplicitlyVisibleOnly =
7151                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7152                final boolean isCallerInstantApp =
7153                        instantAppPkgName != null;
7154                final boolean isTargetSameInstantApp =
7155                        comp.getPackageName().equals(instantAppPkgName);
7156                final boolean isTargetInstantApp =
7157                        (ai.applicationInfo.privateFlags
7158                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7159                final boolean isTargetVisibleToInstantApp =
7160                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7161                final boolean isTargetExplicitlyVisibleToInstantApp =
7162                        isTargetVisibleToInstantApp
7163                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7164                final boolean isTargetHiddenFromInstantApp =
7165                        !isTargetVisibleToInstantApp
7166                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7167                final boolean blockResolution =
7168                        !isTargetSameInstantApp
7169                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7170                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7171                                        && isTargetHiddenFromInstantApp));
7172                if (!blockResolution) {
7173                    final ResolveInfo ri = new ResolveInfo();
7174                    ri.activityInfo = ai;
7175                    list.add(ri);
7176                }
7177            }
7178            return applyPostResolutionFilter(
7179                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7180        }
7181
7182        // reader
7183        boolean sortResult = false;
7184        boolean addEphemeral = false;
7185        List<ResolveInfo> result;
7186        final boolean ephemeralDisabled = isEphemeralDisabled();
7187        synchronized (mPackages) {
7188            if (pkgName == null) {
7189                List<CrossProfileIntentFilter> matchingFilters =
7190                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7191                // Check for results that need to skip the current profile.
7192                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7193                        resolvedType, flags, userId);
7194                if (xpResolveInfo != null) {
7195                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7196                    xpResult.add(xpResolveInfo);
7197                    return applyPostResolutionFilter(
7198                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7199                            allowDynamicSplits, filterCallingUid, userId);
7200                }
7201
7202                // Check for results in the current profile.
7203                result = filterIfNotSystemUser(mActivities.queryIntent(
7204                        intent, resolvedType, flags, userId), userId);
7205                addEphemeral = !ephemeralDisabled
7206                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7207                // Check for cross profile results.
7208                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7209                xpResolveInfo = queryCrossProfileIntents(
7210                        matchingFilters, intent, resolvedType, flags, userId,
7211                        hasNonNegativePriorityResult);
7212                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7213                    boolean isVisibleToUser = filterIfNotSystemUser(
7214                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7215                    if (isVisibleToUser) {
7216                        result.add(xpResolveInfo);
7217                        sortResult = true;
7218                    }
7219                }
7220                if (hasWebURI(intent)) {
7221                    CrossProfileDomainInfo xpDomainInfo = null;
7222                    final UserInfo parent = getProfileParent(userId);
7223                    if (parent != null) {
7224                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7225                                flags, userId, parent.id);
7226                    }
7227                    if (xpDomainInfo != null) {
7228                        if (xpResolveInfo != null) {
7229                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7230                            // in the result.
7231                            result.remove(xpResolveInfo);
7232                        }
7233                        if (result.size() == 0 && !addEphemeral) {
7234                            // No result in current profile, but found candidate in parent user.
7235                            // And we are not going to add emphemeral app, so we can return the
7236                            // result straight away.
7237                            result.add(xpDomainInfo.resolveInfo);
7238                            return applyPostResolutionFilter(result, instantAppPkgName,
7239                                    allowDynamicSplits, filterCallingUid, userId);
7240                        }
7241                    } else if (result.size() <= 1 && !addEphemeral) {
7242                        // No result in parent user and <= 1 result in current profile, and we
7243                        // are not going to add emphemeral app, so we can return the result without
7244                        // further processing.
7245                        return applyPostResolutionFilter(result, instantAppPkgName,
7246                                allowDynamicSplits, filterCallingUid, userId);
7247                    }
7248                    // We have more than one candidate (combining results from current and parent
7249                    // profile), so we need filtering and sorting.
7250                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7251                            intent, flags, result, xpDomainInfo, userId);
7252                    sortResult = true;
7253                }
7254            } else {
7255                final PackageParser.Package pkg = mPackages.get(pkgName);
7256                result = null;
7257                if (pkg != null) {
7258                    result = filterIfNotSystemUser(
7259                            mActivities.queryIntentForPackage(
7260                                    intent, resolvedType, flags, pkg.activities, userId),
7261                            userId);
7262                }
7263                if (result == null || result.size() == 0) {
7264                    // the caller wants to resolve for a particular package; however, there
7265                    // were no installed results, so, try to find an ephemeral result
7266                    addEphemeral = !ephemeralDisabled
7267                            && isInstantAppAllowed(
7268                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7269                    if (result == null) {
7270                        result = new ArrayList<>();
7271                    }
7272                }
7273            }
7274        }
7275        if (addEphemeral) {
7276            result = maybeAddInstantAppInstaller(
7277                    result, intent, resolvedType, flags, userId, resolveForStart);
7278        }
7279        if (sortResult) {
7280            Collections.sort(result, mResolvePrioritySorter);
7281        }
7282        return applyPostResolutionFilter(
7283                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7284    }
7285
7286    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7287            String resolvedType, int flags, int userId, boolean resolveForStart) {
7288        // first, check to see if we've got an instant app already installed
7289        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7290        ResolveInfo localInstantApp = null;
7291        boolean blockResolution = false;
7292        if (!alreadyResolvedLocally) {
7293            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7294                    flags
7295                        | PackageManager.GET_RESOLVED_FILTER
7296                        | PackageManager.MATCH_INSTANT
7297                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7298                    userId);
7299            for (int i = instantApps.size() - 1; i >= 0; --i) {
7300                final ResolveInfo info = instantApps.get(i);
7301                final String packageName = info.activityInfo.packageName;
7302                final PackageSetting ps = mSettings.mPackages.get(packageName);
7303                if (ps.getInstantApp(userId)) {
7304                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7305                    final int status = (int)(packedStatus >> 32);
7306                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7307                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7308                        // there's a local instant application installed, but, the user has
7309                        // chosen to never use it; skip resolution and don't acknowledge
7310                        // an instant application is even available
7311                        if (DEBUG_EPHEMERAL) {
7312                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7313                        }
7314                        blockResolution = true;
7315                        break;
7316                    } else {
7317                        // we have a locally installed instant application; skip resolution
7318                        // but acknowledge there's an instant application available
7319                        if (DEBUG_EPHEMERAL) {
7320                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7321                        }
7322                        localInstantApp = info;
7323                        break;
7324                    }
7325                }
7326            }
7327        }
7328        // no app installed, let's see if one's available
7329        AuxiliaryResolveInfo auxiliaryResponse = null;
7330        if (!blockResolution) {
7331            if (localInstantApp == null) {
7332                // we don't have an instant app locally, resolve externally
7333                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7334                final InstantAppRequest requestObject = new InstantAppRequest(
7335                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7336                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7337                        resolveForStart);
7338                auxiliaryResponse =
7339                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7340                                mContext, mInstantAppResolverConnection, requestObject);
7341                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7342            } else {
7343                // we have an instant application locally, but, we can't admit that since
7344                // callers shouldn't be able to determine prior browsing. create a dummy
7345                // auxiliary response so the downstream code behaves as if there's an
7346                // instant application available externally. when it comes time to start
7347                // the instant application, we'll do the right thing.
7348                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7349                auxiliaryResponse = new AuxiliaryResolveInfo(
7350                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7351                        ai.versionCode, null /*failureIntent*/);
7352            }
7353        }
7354        if (auxiliaryResponse != null) {
7355            if (DEBUG_EPHEMERAL) {
7356                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7357            }
7358            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7359            final PackageSetting ps =
7360                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7361            if (ps != null) {
7362                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7363                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7364                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7365                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7366                // make sure this resolver is the default
7367                ephemeralInstaller.isDefault = true;
7368                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7369                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7370                // add a non-generic filter
7371                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7372                ephemeralInstaller.filter.addDataPath(
7373                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7374                ephemeralInstaller.isInstantAppAvailable = true;
7375                result.add(ephemeralInstaller);
7376            }
7377        }
7378        return result;
7379    }
7380
7381    private static class CrossProfileDomainInfo {
7382        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7383        ResolveInfo resolveInfo;
7384        /* Best domain verification status of the activities found in the other profile */
7385        int bestDomainVerificationStatus;
7386    }
7387
7388    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7389            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7390        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7391                sourceUserId)) {
7392            return null;
7393        }
7394        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7395                resolvedType, flags, parentUserId);
7396
7397        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7398            return null;
7399        }
7400        CrossProfileDomainInfo result = null;
7401        int size = resultTargetUser.size();
7402        for (int i = 0; i < size; i++) {
7403            ResolveInfo riTargetUser = resultTargetUser.get(i);
7404            // Intent filter verification is only for filters that specify a host. So don't return
7405            // those that handle all web uris.
7406            if (riTargetUser.handleAllWebDataURI) {
7407                continue;
7408            }
7409            String packageName = riTargetUser.activityInfo.packageName;
7410            PackageSetting ps = mSettings.mPackages.get(packageName);
7411            if (ps == null) {
7412                continue;
7413            }
7414            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7415            int status = (int)(verificationState >> 32);
7416            if (result == null) {
7417                result = new CrossProfileDomainInfo();
7418                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7419                        sourceUserId, parentUserId);
7420                result.bestDomainVerificationStatus = status;
7421            } else {
7422                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7423                        result.bestDomainVerificationStatus);
7424            }
7425        }
7426        // Don't consider matches with status NEVER across profiles.
7427        if (result != null && result.bestDomainVerificationStatus
7428                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7429            return null;
7430        }
7431        return result;
7432    }
7433
7434    /**
7435     * Verification statuses are ordered from the worse to the best, except for
7436     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7437     */
7438    private int bestDomainVerificationStatus(int status1, int status2) {
7439        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7440            return status2;
7441        }
7442        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7443            return status1;
7444        }
7445        return (int) MathUtils.max(status1, status2);
7446    }
7447
7448    private boolean isUserEnabled(int userId) {
7449        long callingId = Binder.clearCallingIdentity();
7450        try {
7451            UserInfo userInfo = sUserManager.getUserInfo(userId);
7452            return userInfo != null && userInfo.isEnabled();
7453        } finally {
7454            Binder.restoreCallingIdentity(callingId);
7455        }
7456    }
7457
7458    /**
7459     * Filter out activities with systemUserOnly flag set, when current user is not System.
7460     *
7461     * @return filtered list
7462     */
7463    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7464        if (userId == UserHandle.USER_SYSTEM) {
7465            return resolveInfos;
7466        }
7467        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7468            ResolveInfo info = resolveInfos.get(i);
7469            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7470                resolveInfos.remove(i);
7471            }
7472        }
7473        return resolveInfos;
7474    }
7475
7476    /**
7477     * Filters out ephemeral activities.
7478     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7479     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7480     *
7481     * @param resolveInfos The pre-filtered list of resolved activities
7482     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7483     *          is performed.
7484     * @return A filtered list of resolved activities.
7485     */
7486    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7487            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7488        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7489            final ResolveInfo info = resolveInfos.get(i);
7490            // allow activities that are defined in the provided package
7491            if (allowDynamicSplits
7492                    && info.activityInfo.splitName != null
7493                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7494                            info.activityInfo.splitName)) {
7495                // requested activity is defined in a split that hasn't been installed yet.
7496                // add the installer to the resolve list
7497                if (DEBUG_INSTALL) {
7498                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7499                }
7500                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7501                final ComponentName installFailureActivity = findInstallFailureActivity(
7502                        info.activityInfo.packageName,  filterCallingUid, userId);
7503                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7504                        info.activityInfo.packageName, info.activityInfo.splitName,
7505                        installFailureActivity,
7506                        info.activityInfo.applicationInfo.versionCode,
7507                        null /*failureIntent*/);
7508                // make sure this resolver is the default
7509                installerInfo.isDefault = true;
7510                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7511                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7512                // add a non-generic filter
7513                installerInfo.filter = new IntentFilter();
7514                // load resources from the correct package
7515                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7516                resolveInfos.set(i, installerInfo);
7517                continue;
7518            }
7519            // caller is a full app, don't need to apply any other filtering
7520            if (ephemeralPkgName == null) {
7521                continue;
7522            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7523                // caller is same app; don't need to apply any other filtering
7524                continue;
7525            }
7526            // allow activities that have been explicitly exposed to ephemeral apps
7527            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7528            if (!isEphemeralApp
7529                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7530                continue;
7531            }
7532            resolveInfos.remove(i);
7533        }
7534        return resolveInfos;
7535    }
7536
7537    /**
7538     * Returns the activity component that can handle install failures.
7539     * <p>By default, the instant application installer handles failures. However, an
7540     * application may want to handle failures on its own. Applications do this by
7541     * creating an activity with an intent filter that handles the action
7542     * {@link Intent#ACTION_INSTALL_FAILURE}.
7543     */
7544    private @Nullable ComponentName findInstallFailureActivity(
7545            String packageName, int filterCallingUid, int userId) {
7546        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7547        failureActivityIntent.setPackage(packageName);
7548        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7549        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7550                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7551                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7552        final int NR = result.size();
7553        if (NR > 0) {
7554            for (int i = 0; i < NR; i++) {
7555                final ResolveInfo info = result.get(i);
7556                if (info.activityInfo.splitName != null) {
7557                    continue;
7558                }
7559                return new ComponentName(packageName, info.activityInfo.name);
7560            }
7561        }
7562        return null;
7563    }
7564
7565    /**
7566     * @param resolveInfos list of resolve infos in descending priority order
7567     * @return if the list contains a resolve info with non-negative priority
7568     */
7569    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7570        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7571    }
7572
7573    private static boolean hasWebURI(Intent intent) {
7574        if (intent.getData() == null) {
7575            return false;
7576        }
7577        final String scheme = intent.getScheme();
7578        if (TextUtils.isEmpty(scheme)) {
7579            return false;
7580        }
7581        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7582    }
7583
7584    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7585            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7586            int userId) {
7587        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7588
7589        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7590            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7591                    candidates.size());
7592        }
7593
7594        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7595        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7596        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7597        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7598        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7599        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7600
7601        synchronized (mPackages) {
7602            final int count = candidates.size();
7603            // First, try to use linked apps. Partition the candidates into four lists:
7604            // one for the final results, one for the "do not use ever", one for "undefined status"
7605            // and finally one for "browser app type".
7606            for (int n=0; n<count; n++) {
7607                ResolveInfo info = candidates.get(n);
7608                String packageName = info.activityInfo.packageName;
7609                PackageSetting ps = mSettings.mPackages.get(packageName);
7610                if (ps != null) {
7611                    // Add to the special match all list (Browser use case)
7612                    if (info.handleAllWebDataURI) {
7613                        matchAllList.add(info);
7614                        continue;
7615                    }
7616                    // Try to get the status from User settings first
7617                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7618                    int status = (int)(packedStatus >> 32);
7619                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7620                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7621                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7622                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7623                                    + " : linkgen=" + linkGeneration);
7624                        }
7625                        // Use link-enabled generation as preferredOrder, i.e.
7626                        // prefer newly-enabled over earlier-enabled.
7627                        info.preferredOrder = linkGeneration;
7628                        alwaysList.add(info);
7629                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7630                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7631                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7632                        }
7633                        neverList.add(info);
7634                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7635                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7636                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7637                        }
7638                        alwaysAskList.add(info);
7639                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7640                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7641                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7642                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7643                        }
7644                        undefinedList.add(info);
7645                    }
7646                }
7647            }
7648
7649            // We'll want to include browser possibilities in a few cases
7650            boolean includeBrowser = false;
7651
7652            // First try to add the "always" resolution(s) for the current user, if any
7653            if (alwaysList.size() > 0) {
7654                result.addAll(alwaysList);
7655            } else {
7656                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7657                result.addAll(undefinedList);
7658                // Maybe add one for the other profile.
7659                if (xpDomainInfo != null && (
7660                        xpDomainInfo.bestDomainVerificationStatus
7661                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7662                    result.add(xpDomainInfo.resolveInfo);
7663                }
7664                includeBrowser = true;
7665            }
7666
7667            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7668            // If there were 'always' entries their preferred order has been set, so we also
7669            // back that off to make the alternatives equivalent
7670            if (alwaysAskList.size() > 0) {
7671                for (ResolveInfo i : result) {
7672                    i.preferredOrder = 0;
7673                }
7674                result.addAll(alwaysAskList);
7675                includeBrowser = true;
7676            }
7677
7678            if (includeBrowser) {
7679                // Also add browsers (all of them or only the default one)
7680                if (DEBUG_DOMAIN_VERIFICATION) {
7681                    Slog.v(TAG, "   ...including browsers in candidate set");
7682                }
7683                if ((matchFlags & MATCH_ALL) != 0) {
7684                    result.addAll(matchAllList);
7685                } else {
7686                    // Browser/generic handling case.  If there's a default browser, go straight
7687                    // to that (but only if there is no other higher-priority match).
7688                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7689                    int maxMatchPrio = 0;
7690                    ResolveInfo defaultBrowserMatch = null;
7691                    final int numCandidates = matchAllList.size();
7692                    for (int n = 0; n < numCandidates; n++) {
7693                        ResolveInfo info = matchAllList.get(n);
7694                        // track the highest overall match priority...
7695                        if (info.priority > maxMatchPrio) {
7696                            maxMatchPrio = info.priority;
7697                        }
7698                        // ...and the highest-priority default browser match
7699                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7700                            if (defaultBrowserMatch == null
7701                                    || (defaultBrowserMatch.priority < info.priority)) {
7702                                if (debug) {
7703                                    Slog.v(TAG, "Considering default browser match " + info);
7704                                }
7705                                defaultBrowserMatch = info;
7706                            }
7707                        }
7708                    }
7709                    if (defaultBrowserMatch != null
7710                            && defaultBrowserMatch.priority >= maxMatchPrio
7711                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7712                    {
7713                        if (debug) {
7714                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7715                        }
7716                        result.add(defaultBrowserMatch);
7717                    } else {
7718                        result.addAll(matchAllList);
7719                    }
7720                }
7721
7722                // If there is nothing selected, add all candidates and remove the ones that the user
7723                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7724                if (result.size() == 0) {
7725                    result.addAll(candidates);
7726                    result.removeAll(neverList);
7727                }
7728            }
7729        }
7730        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7731            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7732                    result.size());
7733            for (ResolveInfo info : result) {
7734                Slog.v(TAG, "  + " + info.activityInfo);
7735            }
7736        }
7737        return result;
7738    }
7739
7740    // Returns a packed value as a long:
7741    //
7742    // high 'int'-sized word: link status: undefined/ask/never/always.
7743    // low 'int'-sized word: relative priority among 'always' results.
7744    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7745        long result = ps.getDomainVerificationStatusForUser(userId);
7746        // if none available, get the master status
7747        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7748            if (ps.getIntentFilterVerificationInfo() != null) {
7749                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7750            }
7751        }
7752        return result;
7753    }
7754
7755    private ResolveInfo querySkipCurrentProfileIntents(
7756            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7757            int flags, int sourceUserId) {
7758        if (matchingFilters != null) {
7759            int size = matchingFilters.size();
7760            for (int i = 0; i < size; i ++) {
7761                CrossProfileIntentFilter filter = matchingFilters.get(i);
7762                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7763                    // Checking if there are activities in the target user that can handle the
7764                    // intent.
7765                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7766                            resolvedType, flags, sourceUserId);
7767                    if (resolveInfo != null) {
7768                        return resolveInfo;
7769                    }
7770                }
7771            }
7772        }
7773        return null;
7774    }
7775
7776    // Return matching ResolveInfo in target user if any.
7777    private ResolveInfo queryCrossProfileIntents(
7778            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7779            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7780        if (matchingFilters != null) {
7781            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7782            // match the same intent. For performance reasons, it is better not to
7783            // run queryIntent twice for the same userId
7784            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7785            int size = matchingFilters.size();
7786            for (int i = 0; i < size; i++) {
7787                CrossProfileIntentFilter filter = matchingFilters.get(i);
7788                int targetUserId = filter.getTargetUserId();
7789                boolean skipCurrentProfile =
7790                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7791                boolean skipCurrentProfileIfNoMatchFound =
7792                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7793                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7794                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7795                    // Checking if there are activities in the target user that can handle the
7796                    // intent.
7797                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7798                            resolvedType, flags, sourceUserId);
7799                    if (resolveInfo != null) return resolveInfo;
7800                    alreadyTriedUserIds.put(targetUserId, true);
7801                }
7802            }
7803        }
7804        return null;
7805    }
7806
7807    /**
7808     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7809     * will forward the intent to the filter's target user.
7810     * Otherwise, returns null.
7811     */
7812    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7813            String resolvedType, int flags, int sourceUserId) {
7814        int targetUserId = filter.getTargetUserId();
7815        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7816                resolvedType, flags, targetUserId);
7817        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7818            // If all the matches in the target profile are suspended, return null.
7819            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7820                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7821                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7822                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7823                            targetUserId);
7824                }
7825            }
7826        }
7827        return null;
7828    }
7829
7830    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7831            int sourceUserId, int targetUserId) {
7832        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7833        long ident = Binder.clearCallingIdentity();
7834        boolean targetIsProfile;
7835        try {
7836            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7837        } finally {
7838            Binder.restoreCallingIdentity(ident);
7839        }
7840        String className;
7841        if (targetIsProfile) {
7842            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7843        } else {
7844            className = FORWARD_INTENT_TO_PARENT;
7845        }
7846        ComponentName forwardingActivityComponentName = new ComponentName(
7847                mAndroidApplication.packageName, className);
7848        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7849                sourceUserId);
7850        if (!targetIsProfile) {
7851            forwardingActivityInfo.showUserIcon = targetUserId;
7852            forwardingResolveInfo.noResourceId = true;
7853        }
7854        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7855        forwardingResolveInfo.priority = 0;
7856        forwardingResolveInfo.preferredOrder = 0;
7857        forwardingResolveInfo.match = 0;
7858        forwardingResolveInfo.isDefault = true;
7859        forwardingResolveInfo.filter = filter;
7860        forwardingResolveInfo.targetUserId = targetUserId;
7861        return forwardingResolveInfo;
7862    }
7863
7864    @Override
7865    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7866            Intent[] specifics, String[] specificTypes, Intent intent,
7867            String resolvedType, int flags, int userId) {
7868        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7869                specificTypes, intent, resolvedType, flags, userId));
7870    }
7871
7872    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7873            Intent[] specifics, String[] specificTypes, Intent intent,
7874            String resolvedType, int flags, int userId) {
7875        if (!sUserManager.exists(userId)) return Collections.emptyList();
7876        final int callingUid = Binder.getCallingUid();
7877        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7878                false /*includeInstantApps*/);
7879        enforceCrossUserPermission(callingUid, userId,
7880                false /*requireFullPermission*/, false /*checkShell*/,
7881                "query intent activity options");
7882        final String resultsAction = intent.getAction();
7883
7884        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7885                | PackageManager.GET_RESOLVED_FILTER, userId);
7886
7887        if (DEBUG_INTENT_MATCHING) {
7888            Log.v(TAG, "Query " + intent + ": " + results);
7889        }
7890
7891        int specificsPos = 0;
7892        int N;
7893
7894        // todo: note that the algorithm used here is O(N^2).  This
7895        // isn't a problem in our current environment, but if we start running
7896        // into situations where we have more than 5 or 10 matches then this
7897        // should probably be changed to something smarter...
7898
7899        // First we go through and resolve each of the specific items
7900        // that were supplied, taking care of removing any corresponding
7901        // duplicate items in the generic resolve list.
7902        if (specifics != null) {
7903            for (int i=0; i<specifics.length; i++) {
7904                final Intent sintent = specifics[i];
7905                if (sintent == null) {
7906                    continue;
7907                }
7908
7909                if (DEBUG_INTENT_MATCHING) {
7910                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7911                }
7912
7913                String action = sintent.getAction();
7914                if (resultsAction != null && resultsAction.equals(action)) {
7915                    // If this action was explicitly requested, then don't
7916                    // remove things that have it.
7917                    action = null;
7918                }
7919
7920                ResolveInfo ri = null;
7921                ActivityInfo ai = null;
7922
7923                ComponentName comp = sintent.getComponent();
7924                if (comp == null) {
7925                    ri = resolveIntent(
7926                        sintent,
7927                        specificTypes != null ? specificTypes[i] : null,
7928                            flags, userId);
7929                    if (ri == null) {
7930                        continue;
7931                    }
7932                    if (ri == mResolveInfo) {
7933                        // ACK!  Must do something better with this.
7934                    }
7935                    ai = ri.activityInfo;
7936                    comp = new ComponentName(ai.applicationInfo.packageName,
7937                            ai.name);
7938                } else {
7939                    ai = getActivityInfo(comp, flags, userId);
7940                    if (ai == null) {
7941                        continue;
7942                    }
7943                }
7944
7945                // Look for any generic query activities that are duplicates
7946                // of this specific one, and remove them from the results.
7947                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7948                N = results.size();
7949                int j;
7950                for (j=specificsPos; j<N; j++) {
7951                    ResolveInfo sri = results.get(j);
7952                    if ((sri.activityInfo.name.equals(comp.getClassName())
7953                            && sri.activityInfo.applicationInfo.packageName.equals(
7954                                    comp.getPackageName()))
7955                        || (action != null && sri.filter.matchAction(action))) {
7956                        results.remove(j);
7957                        if (DEBUG_INTENT_MATCHING) Log.v(
7958                            TAG, "Removing duplicate item from " + j
7959                            + " due to specific " + specificsPos);
7960                        if (ri == null) {
7961                            ri = sri;
7962                        }
7963                        j--;
7964                        N--;
7965                    }
7966                }
7967
7968                // Add this specific item to its proper place.
7969                if (ri == null) {
7970                    ri = new ResolveInfo();
7971                    ri.activityInfo = ai;
7972                }
7973                results.add(specificsPos, ri);
7974                ri.specificIndex = i;
7975                specificsPos++;
7976            }
7977        }
7978
7979        // Now we go through the remaining generic results and remove any
7980        // duplicate actions that are found here.
7981        N = results.size();
7982        for (int i=specificsPos; i<N-1; i++) {
7983            final ResolveInfo rii = results.get(i);
7984            if (rii.filter == null) {
7985                continue;
7986            }
7987
7988            // Iterate over all of the actions of this result's intent
7989            // filter...  typically this should be just one.
7990            final Iterator<String> it = rii.filter.actionsIterator();
7991            if (it == null) {
7992                continue;
7993            }
7994            while (it.hasNext()) {
7995                final String action = it.next();
7996                if (resultsAction != null && resultsAction.equals(action)) {
7997                    // If this action was explicitly requested, then don't
7998                    // remove things that have it.
7999                    continue;
8000                }
8001                for (int j=i+1; j<N; j++) {
8002                    final ResolveInfo rij = results.get(j);
8003                    if (rij.filter != null && rij.filter.hasAction(action)) {
8004                        results.remove(j);
8005                        if (DEBUG_INTENT_MATCHING) Log.v(
8006                            TAG, "Removing duplicate item from " + j
8007                            + " due to action " + action + " at " + i);
8008                        j--;
8009                        N--;
8010                    }
8011                }
8012            }
8013
8014            // If the caller didn't request filter information, drop it now
8015            // so we don't have to marshall/unmarshall it.
8016            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8017                rii.filter = null;
8018            }
8019        }
8020
8021        // Filter out the caller activity if so requested.
8022        if (caller != null) {
8023            N = results.size();
8024            for (int i=0; i<N; i++) {
8025                ActivityInfo ainfo = results.get(i).activityInfo;
8026                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8027                        && caller.getClassName().equals(ainfo.name)) {
8028                    results.remove(i);
8029                    break;
8030                }
8031            }
8032        }
8033
8034        // If the caller didn't request filter information,
8035        // drop them now so we don't have to
8036        // marshall/unmarshall it.
8037        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8038            N = results.size();
8039            for (int i=0; i<N; i++) {
8040                results.get(i).filter = null;
8041            }
8042        }
8043
8044        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8045        return results;
8046    }
8047
8048    @Override
8049    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8050            String resolvedType, int flags, int userId) {
8051        return new ParceledListSlice<>(
8052                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8053                        false /*allowDynamicSplits*/));
8054    }
8055
8056    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8057            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8058        if (!sUserManager.exists(userId)) return Collections.emptyList();
8059        final int callingUid = Binder.getCallingUid();
8060        enforceCrossUserPermission(callingUid, userId,
8061                false /*requireFullPermission*/, false /*checkShell*/,
8062                "query intent receivers");
8063        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8064        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8065                false /*includeInstantApps*/);
8066        ComponentName comp = intent.getComponent();
8067        if (comp == null) {
8068            if (intent.getSelector() != null) {
8069                intent = intent.getSelector();
8070                comp = intent.getComponent();
8071            }
8072        }
8073        if (comp != null) {
8074            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8075            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8076            if (ai != null) {
8077                // When specifying an explicit component, we prevent the activity from being
8078                // used when either 1) the calling package is normal and the activity is within
8079                // an instant application or 2) the calling package is ephemeral and the
8080                // activity is not visible to instant applications.
8081                final boolean matchInstantApp =
8082                        (flags & PackageManager.MATCH_INSTANT) != 0;
8083                final boolean matchVisibleToInstantAppOnly =
8084                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8085                final boolean matchExplicitlyVisibleOnly =
8086                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8087                final boolean isCallerInstantApp =
8088                        instantAppPkgName != null;
8089                final boolean isTargetSameInstantApp =
8090                        comp.getPackageName().equals(instantAppPkgName);
8091                final boolean isTargetInstantApp =
8092                        (ai.applicationInfo.privateFlags
8093                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8094                final boolean isTargetVisibleToInstantApp =
8095                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8096                final boolean isTargetExplicitlyVisibleToInstantApp =
8097                        isTargetVisibleToInstantApp
8098                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8099                final boolean isTargetHiddenFromInstantApp =
8100                        !isTargetVisibleToInstantApp
8101                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8102                final boolean blockResolution =
8103                        !isTargetSameInstantApp
8104                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8105                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8106                                        && isTargetHiddenFromInstantApp));
8107                if (!blockResolution) {
8108                    ResolveInfo ri = new ResolveInfo();
8109                    ri.activityInfo = ai;
8110                    list.add(ri);
8111                }
8112            }
8113            return applyPostResolutionFilter(
8114                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8115        }
8116
8117        // reader
8118        synchronized (mPackages) {
8119            String pkgName = intent.getPackage();
8120            if (pkgName == null) {
8121                final List<ResolveInfo> result =
8122                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8123                return applyPostResolutionFilter(
8124                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8125            }
8126            final PackageParser.Package pkg = mPackages.get(pkgName);
8127            if (pkg != null) {
8128                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8129                        intent, resolvedType, flags, pkg.receivers, userId);
8130                return applyPostResolutionFilter(
8131                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8132            }
8133            return Collections.emptyList();
8134        }
8135    }
8136
8137    @Override
8138    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8139        final int callingUid = Binder.getCallingUid();
8140        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8141    }
8142
8143    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8144            int userId, int callingUid) {
8145        if (!sUserManager.exists(userId)) return null;
8146        flags = updateFlagsForResolve(
8147                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8148        List<ResolveInfo> query = queryIntentServicesInternal(
8149                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8150        if (query != null) {
8151            if (query.size() >= 1) {
8152                // If there is more than one service with the same priority,
8153                // just arbitrarily pick the first one.
8154                return query.get(0);
8155            }
8156        }
8157        return null;
8158    }
8159
8160    @Override
8161    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8162            String resolvedType, int flags, int userId) {
8163        final int callingUid = Binder.getCallingUid();
8164        return new ParceledListSlice<>(queryIntentServicesInternal(
8165                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8166    }
8167
8168    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8169            String resolvedType, int flags, int userId, int callingUid,
8170            boolean includeInstantApps) {
8171        if (!sUserManager.exists(userId)) return Collections.emptyList();
8172        enforceCrossUserPermission(callingUid, userId,
8173                false /*requireFullPermission*/, false /*checkShell*/,
8174                "query intent receivers");
8175        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8176        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8177        ComponentName comp = intent.getComponent();
8178        if (comp == null) {
8179            if (intent.getSelector() != null) {
8180                intent = intent.getSelector();
8181                comp = intent.getComponent();
8182            }
8183        }
8184        if (comp != null) {
8185            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8186            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8187            if (si != null) {
8188                // When specifying an explicit component, we prevent the service from being
8189                // used when either 1) the service is in an instant application and the
8190                // caller is not the same instant application or 2) the calling package is
8191                // ephemeral and the activity is not visible to ephemeral applications.
8192                final boolean matchInstantApp =
8193                        (flags & PackageManager.MATCH_INSTANT) != 0;
8194                final boolean matchVisibleToInstantAppOnly =
8195                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8196                final boolean isCallerInstantApp =
8197                        instantAppPkgName != null;
8198                final boolean isTargetSameInstantApp =
8199                        comp.getPackageName().equals(instantAppPkgName);
8200                final boolean isTargetInstantApp =
8201                        (si.applicationInfo.privateFlags
8202                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8203                final boolean isTargetHiddenFromInstantApp =
8204                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8205                final boolean blockResolution =
8206                        !isTargetSameInstantApp
8207                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8208                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8209                                        && isTargetHiddenFromInstantApp));
8210                if (!blockResolution) {
8211                    final ResolveInfo ri = new ResolveInfo();
8212                    ri.serviceInfo = si;
8213                    list.add(ri);
8214                }
8215            }
8216            return list;
8217        }
8218
8219        // reader
8220        synchronized (mPackages) {
8221            String pkgName = intent.getPackage();
8222            if (pkgName == null) {
8223                return applyPostServiceResolutionFilter(
8224                        mServices.queryIntent(intent, resolvedType, flags, userId),
8225                        instantAppPkgName);
8226            }
8227            final PackageParser.Package pkg = mPackages.get(pkgName);
8228            if (pkg != null) {
8229                return applyPostServiceResolutionFilter(
8230                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8231                                userId),
8232                        instantAppPkgName);
8233            }
8234            return Collections.emptyList();
8235        }
8236    }
8237
8238    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8239            String instantAppPkgName) {
8240        if (instantAppPkgName == null) {
8241            return resolveInfos;
8242        }
8243        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8244            final ResolveInfo info = resolveInfos.get(i);
8245            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8246            // allow services that are defined in the provided package
8247            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8248                if (info.serviceInfo.splitName != null
8249                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8250                                info.serviceInfo.splitName)) {
8251                    // requested service is defined in a split that hasn't been installed yet.
8252                    // add the installer to the resolve list
8253                    if (DEBUG_EPHEMERAL) {
8254                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8255                    }
8256                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8257                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8258                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8259                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8260                            null /*failureIntent*/);
8261                    // make sure this resolver is the default
8262                    installerInfo.isDefault = true;
8263                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8264                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8265                    // add a non-generic filter
8266                    installerInfo.filter = new IntentFilter();
8267                    // load resources from the correct package
8268                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8269                    resolveInfos.set(i, installerInfo);
8270                }
8271                continue;
8272            }
8273            // allow services that have been explicitly exposed to ephemeral apps
8274            if (!isEphemeralApp
8275                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8276                continue;
8277            }
8278            resolveInfos.remove(i);
8279        }
8280        return resolveInfos;
8281    }
8282
8283    @Override
8284    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8285            String resolvedType, int flags, int userId) {
8286        return new ParceledListSlice<>(
8287                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8288    }
8289
8290    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8291            Intent intent, String resolvedType, int flags, int userId) {
8292        if (!sUserManager.exists(userId)) return Collections.emptyList();
8293        final int callingUid = Binder.getCallingUid();
8294        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8295        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8296                false /*includeInstantApps*/);
8297        ComponentName comp = intent.getComponent();
8298        if (comp == null) {
8299            if (intent.getSelector() != null) {
8300                intent = intent.getSelector();
8301                comp = intent.getComponent();
8302            }
8303        }
8304        if (comp != null) {
8305            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8306            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8307            if (pi != null) {
8308                // When specifying an explicit component, we prevent the provider from being
8309                // used when either 1) the provider is in an instant application and the
8310                // caller is not the same instant application or 2) the calling package is an
8311                // instant application and the provider is not visible to instant applications.
8312                final boolean matchInstantApp =
8313                        (flags & PackageManager.MATCH_INSTANT) != 0;
8314                final boolean matchVisibleToInstantAppOnly =
8315                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8316                final boolean isCallerInstantApp =
8317                        instantAppPkgName != null;
8318                final boolean isTargetSameInstantApp =
8319                        comp.getPackageName().equals(instantAppPkgName);
8320                final boolean isTargetInstantApp =
8321                        (pi.applicationInfo.privateFlags
8322                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8323                final boolean isTargetHiddenFromInstantApp =
8324                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8325                final boolean blockResolution =
8326                        !isTargetSameInstantApp
8327                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8328                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8329                                        && isTargetHiddenFromInstantApp));
8330                if (!blockResolution) {
8331                    final ResolveInfo ri = new ResolveInfo();
8332                    ri.providerInfo = pi;
8333                    list.add(ri);
8334                }
8335            }
8336            return list;
8337        }
8338
8339        // reader
8340        synchronized (mPackages) {
8341            String pkgName = intent.getPackage();
8342            if (pkgName == null) {
8343                return applyPostContentProviderResolutionFilter(
8344                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8345                        instantAppPkgName);
8346            }
8347            final PackageParser.Package pkg = mPackages.get(pkgName);
8348            if (pkg != null) {
8349                return applyPostContentProviderResolutionFilter(
8350                        mProviders.queryIntentForPackage(
8351                        intent, resolvedType, flags, pkg.providers, userId),
8352                        instantAppPkgName);
8353            }
8354            return Collections.emptyList();
8355        }
8356    }
8357
8358    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8359            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8360        if (instantAppPkgName == null) {
8361            return resolveInfos;
8362        }
8363        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8364            final ResolveInfo info = resolveInfos.get(i);
8365            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8366            // allow providers that are defined in the provided package
8367            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8368                if (info.providerInfo.splitName != null
8369                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8370                                info.providerInfo.splitName)) {
8371                    // requested provider is defined in a split that hasn't been installed yet.
8372                    // add the installer to the resolve list
8373                    if (DEBUG_EPHEMERAL) {
8374                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8375                    }
8376                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8377                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8378                            info.providerInfo.packageName, info.providerInfo.splitName,
8379                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8380                            null /*failureIntent*/);
8381                    // make sure this resolver is the default
8382                    installerInfo.isDefault = true;
8383                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8384                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8385                    // add a non-generic filter
8386                    installerInfo.filter = new IntentFilter();
8387                    // load resources from the correct package
8388                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8389                    resolveInfos.set(i, installerInfo);
8390                }
8391                continue;
8392            }
8393            // allow providers that have been explicitly exposed to instant applications
8394            if (!isEphemeralApp
8395                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8396                continue;
8397            }
8398            resolveInfos.remove(i);
8399        }
8400        return resolveInfos;
8401    }
8402
8403    @Override
8404    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8405        final int callingUid = Binder.getCallingUid();
8406        if (getInstantAppPackageName(callingUid) != null) {
8407            return ParceledListSlice.emptyList();
8408        }
8409        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8410        flags = updateFlagsForPackage(flags, userId, null);
8411        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8412        enforceCrossUserPermission(callingUid, userId,
8413                true /* requireFullPermission */, false /* checkShell */,
8414                "get installed packages");
8415
8416        // writer
8417        synchronized (mPackages) {
8418            ArrayList<PackageInfo> list;
8419            if (listUninstalled) {
8420                list = new ArrayList<>(mSettings.mPackages.size());
8421                for (PackageSetting ps : mSettings.mPackages.values()) {
8422                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8423                        continue;
8424                    }
8425                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8426                        continue;
8427                    }
8428                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8429                    if (pi != null) {
8430                        list.add(pi);
8431                    }
8432                }
8433            } else {
8434                list = new ArrayList<>(mPackages.size());
8435                for (PackageParser.Package p : mPackages.values()) {
8436                    final PackageSetting ps = (PackageSetting) p.mExtras;
8437                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8438                        continue;
8439                    }
8440                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8441                        continue;
8442                    }
8443                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8444                            p.mExtras, flags, userId);
8445                    if (pi != null) {
8446                        list.add(pi);
8447                    }
8448                }
8449            }
8450
8451            return new ParceledListSlice<>(list);
8452        }
8453    }
8454
8455    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8456            String[] permissions, boolean[] tmp, int flags, int userId) {
8457        int numMatch = 0;
8458        final PermissionsState permissionsState = ps.getPermissionsState();
8459        for (int i=0; i<permissions.length; i++) {
8460            final String permission = permissions[i];
8461            if (permissionsState.hasPermission(permission, userId)) {
8462                tmp[i] = true;
8463                numMatch++;
8464            } else {
8465                tmp[i] = false;
8466            }
8467        }
8468        if (numMatch == 0) {
8469            return;
8470        }
8471        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8472
8473        // The above might return null in cases of uninstalled apps or install-state
8474        // skew across users/profiles.
8475        if (pi != null) {
8476            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8477                if (numMatch == permissions.length) {
8478                    pi.requestedPermissions = permissions;
8479                } else {
8480                    pi.requestedPermissions = new String[numMatch];
8481                    numMatch = 0;
8482                    for (int i=0; i<permissions.length; i++) {
8483                        if (tmp[i]) {
8484                            pi.requestedPermissions[numMatch] = permissions[i];
8485                            numMatch++;
8486                        }
8487                    }
8488                }
8489            }
8490            list.add(pi);
8491        }
8492    }
8493
8494    @Override
8495    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8496            String[] permissions, int flags, int userId) {
8497        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8498        flags = updateFlagsForPackage(flags, userId, permissions);
8499        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8500                true /* requireFullPermission */, false /* checkShell */,
8501                "get packages holding permissions");
8502        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8503
8504        // writer
8505        synchronized (mPackages) {
8506            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8507            boolean[] tmpBools = new boolean[permissions.length];
8508            if (listUninstalled) {
8509                for (PackageSetting ps : mSettings.mPackages.values()) {
8510                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8511                            userId);
8512                }
8513            } else {
8514                for (PackageParser.Package pkg : mPackages.values()) {
8515                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8516                    if (ps != null) {
8517                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8518                                userId);
8519                    }
8520                }
8521            }
8522
8523            return new ParceledListSlice<PackageInfo>(list);
8524        }
8525    }
8526
8527    @Override
8528    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8529        final int callingUid = Binder.getCallingUid();
8530        if (getInstantAppPackageName(callingUid) != null) {
8531            return ParceledListSlice.emptyList();
8532        }
8533        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8534        flags = updateFlagsForApplication(flags, userId, null);
8535        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8536
8537        // writer
8538        synchronized (mPackages) {
8539            ArrayList<ApplicationInfo> list;
8540            if (listUninstalled) {
8541                list = new ArrayList<>(mSettings.mPackages.size());
8542                for (PackageSetting ps : mSettings.mPackages.values()) {
8543                    ApplicationInfo ai;
8544                    int effectiveFlags = flags;
8545                    if (ps.isSystem()) {
8546                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8547                    }
8548                    if (ps.pkg != null) {
8549                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8550                            continue;
8551                        }
8552                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8553                            continue;
8554                        }
8555                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8556                                ps.readUserState(userId), userId);
8557                        if (ai != null) {
8558                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8559                        }
8560                    } else {
8561                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8562                        // and already converts to externally visible package name
8563                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8564                                callingUid, effectiveFlags, userId);
8565                    }
8566                    if (ai != null) {
8567                        list.add(ai);
8568                    }
8569                }
8570            } else {
8571                list = new ArrayList<>(mPackages.size());
8572                for (PackageParser.Package p : mPackages.values()) {
8573                    if (p.mExtras != null) {
8574                        PackageSetting ps = (PackageSetting) p.mExtras;
8575                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8576                            continue;
8577                        }
8578                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8579                            continue;
8580                        }
8581                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8582                                ps.readUserState(userId), userId);
8583                        if (ai != null) {
8584                            ai.packageName = resolveExternalPackageNameLPr(p);
8585                            list.add(ai);
8586                        }
8587                    }
8588                }
8589            }
8590
8591            return new ParceledListSlice<>(list);
8592        }
8593    }
8594
8595    @Override
8596    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8597        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8598            return null;
8599        }
8600        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8601            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8602                    "getEphemeralApplications");
8603        }
8604        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8605                true /* requireFullPermission */, false /* checkShell */,
8606                "getEphemeralApplications");
8607        synchronized (mPackages) {
8608            List<InstantAppInfo> instantApps = mInstantAppRegistry
8609                    .getInstantAppsLPr(userId);
8610            if (instantApps != null) {
8611                return new ParceledListSlice<>(instantApps);
8612            }
8613        }
8614        return null;
8615    }
8616
8617    @Override
8618    public boolean isInstantApp(String packageName, int userId) {
8619        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8620                true /* requireFullPermission */, false /* checkShell */,
8621                "isInstantApp");
8622        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8623            return false;
8624        }
8625
8626        synchronized (mPackages) {
8627            int callingUid = Binder.getCallingUid();
8628            if (Process.isIsolated(callingUid)) {
8629                callingUid = mIsolatedOwners.get(callingUid);
8630            }
8631            final PackageSetting ps = mSettings.mPackages.get(packageName);
8632            PackageParser.Package pkg = mPackages.get(packageName);
8633            final boolean returnAllowed =
8634                    ps != null
8635                    && (isCallerSameApp(packageName, callingUid)
8636                            || canViewInstantApps(callingUid, userId)
8637                            || mInstantAppRegistry.isInstantAccessGranted(
8638                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8639            if (returnAllowed) {
8640                return ps.getInstantApp(userId);
8641            }
8642        }
8643        return false;
8644    }
8645
8646    @Override
8647    public byte[] getInstantAppCookie(String packageName, int userId) {
8648        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8649            return null;
8650        }
8651
8652        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8653                true /* requireFullPermission */, false /* checkShell */,
8654                "getInstantAppCookie");
8655        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8656            return null;
8657        }
8658        synchronized (mPackages) {
8659            return mInstantAppRegistry.getInstantAppCookieLPw(
8660                    packageName, userId);
8661        }
8662    }
8663
8664    @Override
8665    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8666        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8667            return true;
8668        }
8669
8670        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8671                true /* requireFullPermission */, true /* checkShell */,
8672                "setInstantAppCookie");
8673        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8674            return false;
8675        }
8676        synchronized (mPackages) {
8677            return mInstantAppRegistry.setInstantAppCookieLPw(
8678                    packageName, cookie, userId);
8679        }
8680    }
8681
8682    @Override
8683    public Bitmap getInstantAppIcon(String packageName, int userId) {
8684        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8685            return null;
8686        }
8687
8688        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8689            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8690                    "getInstantAppIcon");
8691        }
8692        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8693                true /* requireFullPermission */, false /* checkShell */,
8694                "getInstantAppIcon");
8695
8696        synchronized (mPackages) {
8697            return mInstantAppRegistry.getInstantAppIconLPw(
8698                    packageName, userId);
8699        }
8700    }
8701
8702    private boolean isCallerSameApp(String packageName, int uid) {
8703        PackageParser.Package pkg = mPackages.get(packageName);
8704        return pkg != null
8705                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8706    }
8707
8708    @Override
8709    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8710        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8711            return ParceledListSlice.emptyList();
8712        }
8713        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8714    }
8715
8716    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8717        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8718
8719        // reader
8720        synchronized (mPackages) {
8721            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8722            final int userId = UserHandle.getCallingUserId();
8723            while (i.hasNext()) {
8724                final PackageParser.Package p = i.next();
8725                if (p.applicationInfo == null) continue;
8726
8727                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8728                        && !p.applicationInfo.isDirectBootAware();
8729                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8730                        && p.applicationInfo.isDirectBootAware();
8731
8732                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8733                        && (!mSafeMode || isSystemApp(p))
8734                        && (matchesUnaware || matchesAware)) {
8735                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8736                    if (ps != null) {
8737                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8738                                ps.readUserState(userId), userId);
8739                        if (ai != null) {
8740                            finalList.add(ai);
8741                        }
8742                    }
8743                }
8744            }
8745        }
8746
8747        return finalList;
8748    }
8749
8750    @Override
8751    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8752        return resolveContentProviderInternal(name, flags, userId);
8753    }
8754
8755    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8756        if (!sUserManager.exists(userId)) return null;
8757        flags = updateFlagsForComponent(flags, userId, name);
8758        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8759        // reader
8760        synchronized (mPackages) {
8761            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8762            PackageSetting ps = provider != null
8763                    ? mSettings.mPackages.get(provider.owner.packageName)
8764                    : null;
8765            if (ps != null) {
8766                final boolean isInstantApp = ps.getInstantApp(userId);
8767                // normal application; filter out instant application provider
8768                if (instantAppPkgName == null && isInstantApp) {
8769                    return null;
8770                }
8771                // instant application; filter out other instant applications
8772                if (instantAppPkgName != null
8773                        && isInstantApp
8774                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8775                    return null;
8776                }
8777                // instant application; filter out non-exposed provider
8778                if (instantAppPkgName != null
8779                        && !isInstantApp
8780                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8781                    return null;
8782                }
8783                // provider not enabled
8784                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8785                    return null;
8786                }
8787                return PackageParser.generateProviderInfo(
8788                        provider, flags, ps.readUserState(userId), userId);
8789            }
8790            return null;
8791        }
8792    }
8793
8794    /**
8795     * @deprecated
8796     */
8797    @Deprecated
8798    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8799        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8800            return;
8801        }
8802        // reader
8803        synchronized (mPackages) {
8804            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8805                    .entrySet().iterator();
8806            final int userId = UserHandle.getCallingUserId();
8807            while (i.hasNext()) {
8808                Map.Entry<String, PackageParser.Provider> entry = i.next();
8809                PackageParser.Provider p = entry.getValue();
8810                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8811
8812                if (ps != null && p.syncable
8813                        && (!mSafeMode || (p.info.applicationInfo.flags
8814                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8815                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8816                            ps.readUserState(userId), userId);
8817                    if (info != null) {
8818                        outNames.add(entry.getKey());
8819                        outInfo.add(info);
8820                    }
8821                }
8822            }
8823        }
8824    }
8825
8826    @Override
8827    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8828            int uid, int flags, String metaDataKey) {
8829        final int callingUid = Binder.getCallingUid();
8830        final int userId = processName != null ? UserHandle.getUserId(uid)
8831                : UserHandle.getCallingUserId();
8832        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8833        flags = updateFlagsForComponent(flags, userId, processName);
8834        ArrayList<ProviderInfo> finalList = null;
8835        // reader
8836        synchronized (mPackages) {
8837            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8838            while (i.hasNext()) {
8839                final PackageParser.Provider p = i.next();
8840                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8841                if (ps != null && p.info.authority != null
8842                        && (processName == null
8843                                || (p.info.processName.equals(processName)
8844                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8845                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8846
8847                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8848                    // parameter.
8849                    if (metaDataKey != null
8850                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8851                        continue;
8852                    }
8853                    final ComponentName component =
8854                            new ComponentName(p.info.packageName, p.info.name);
8855                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8856                        continue;
8857                    }
8858                    if (finalList == null) {
8859                        finalList = new ArrayList<ProviderInfo>(3);
8860                    }
8861                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8862                            ps.readUserState(userId), userId);
8863                    if (info != null) {
8864                        finalList.add(info);
8865                    }
8866                }
8867            }
8868        }
8869
8870        if (finalList != null) {
8871            Collections.sort(finalList, mProviderInitOrderSorter);
8872            return new ParceledListSlice<ProviderInfo>(finalList);
8873        }
8874
8875        return ParceledListSlice.emptyList();
8876    }
8877
8878    @Override
8879    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8880        // reader
8881        synchronized (mPackages) {
8882            final int callingUid = Binder.getCallingUid();
8883            final int callingUserId = UserHandle.getUserId(callingUid);
8884            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8885            if (ps == null) return null;
8886            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8887                return null;
8888            }
8889            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8890            return PackageParser.generateInstrumentationInfo(i, flags);
8891        }
8892    }
8893
8894    @Override
8895    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8896            String targetPackage, int flags) {
8897        final int callingUid = Binder.getCallingUid();
8898        final int callingUserId = UserHandle.getUserId(callingUid);
8899        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8900        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8901            return ParceledListSlice.emptyList();
8902        }
8903        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8904    }
8905
8906    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8907            int flags) {
8908        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8909
8910        // reader
8911        synchronized (mPackages) {
8912            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8913            while (i.hasNext()) {
8914                final PackageParser.Instrumentation p = i.next();
8915                if (targetPackage == null
8916                        || targetPackage.equals(p.info.targetPackage)) {
8917                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8918                            flags);
8919                    if (ii != null) {
8920                        finalList.add(ii);
8921                    }
8922                }
8923            }
8924        }
8925
8926        return finalList;
8927    }
8928
8929    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8930        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8931        try {
8932            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8933        } finally {
8934            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8935        }
8936    }
8937
8938    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8939        final File[] files = dir.listFiles();
8940        if (ArrayUtils.isEmpty(files)) {
8941            Log.d(TAG, "No files in app dir " + dir);
8942            return;
8943        }
8944
8945        if (DEBUG_PACKAGE_SCANNING) {
8946            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8947                    + " flags=0x" + Integer.toHexString(parseFlags));
8948        }
8949        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8950                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8951                mParallelPackageParserCallback);
8952
8953        // Submit files for parsing in parallel
8954        int fileCount = 0;
8955        for (File file : files) {
8956            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8957                    && !PackageInstallerService.isStageName(file.getName());
8958            if (!isPackage) {
8959                // Ignore entries which are not packages
8960                continue;
8961            }
8962            parallelPackageParser.submit(file, parseFlags);
8963            fileCount++;
8964        }
8965
8966        // Process results one by one
8967        for (; fileCount > 0; fileCount--) {
8968            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8969            Throwable throwable = parseResult.throwable;
8970            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8971
8972            if (throwable == null) {
8973                // Static shared libraries have synthetic package names
8974                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8975                    renameStaticSharedLibraryPackage(parseResult.pkg);
8976                }
8977                try {
8978                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8979                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8980                                currentTime, null);
8981                    }
8982                } catch (PackageManagerException e) {
8983                    errorCode = e.error;
8984                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8985                }
8986            } else if (throwable instanceof PackageParser.PackageParserException) {
8987                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8988                        throwable;
8989                errorCode = e.error;
8990                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8991            } else {
8992                throw new IllegalStateException("Unexpected exception occurred while parsing "
8993                        + parseResult.scanFile, throwable);
8994            }
8995
8996            // Delete invalid userdata apps
8997            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8998                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8999                logCriticalInfo(Log.WARN,
9000                        "Deleting invalid package at " + parseResult.scanFile);
9001                removeCodePathLI(parseResult.scanFile);
9002            }
9003        }
9004        parallelPackageParser.close();
9005    }
9006
9007    private static File getSettingsProblemFile() {
9008        File dataDir = Environment.getDataDirectory();
9009        File systemDir = new File(dataDir, "system");
9010        File fname = new File(systemDir, "uiderrors.txt");
9011        return fname;
9012    }
9013
9014    public static void reportSettingsProblem(int priority, String msg) {
9015        logCriticalInfo(priority, msg);
9016    }
9017
9018    public static void logCriticalInfo(int priority, String msg) {
9019        Slog.println(priority, TAG, msg);
9020        EventLogTags.writePmCriticalInfo(msg);
9021        try {
9022            File fname = getSettingsProblemFile();
9023            FileOutputStream out = new FileOutputStream(fname, true);
9024            PrintWriter pw = new FastPrintWriter(out);
9025            SimpleDateFormat formatter = new SimpleDateFormat();
9026            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9027            pw.println(dateString + ": " + msg);
9028            pw.close();
9029            FileUtils.setPermissions(
9030                    fname.toString(),
9031                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9032                    -1, -1);
9033        } catch (java.io.IOException e) {
9034        }
9035    }
9036
9037    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9038        if (srcFile.isDirectory()) {
9039            final File baseFile = new File(pkg.baseCodePath);
9040            long maxModifiedTime = baseFile.lastModified();
9041            if (pkg.splitCodePaths != null) {
9042                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9043                    final File splitFile = new File(pkg.splitCodePaths[i]);
9044                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9045                }
9046            }
9047            return maxModifiedTime;
9048        }
9049        return srcFile.lastModified();
9050    }
9051
9052    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9053            final int policyFlags) throws PackageManagerException {
9054        // When upgrading from pre-N MR1, verify the package time stamp using the package
9055        // directory and not the APK file.
9056        final long lastModifiedTime = mIsPreNMR1Upgrade
9057                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9058        if (ps != null
9059                && ps.codePath.equals(srcFile)
9060                && ps.timeStamp == lastModifiedTime
9061                && !isCompatSignatureUpdateNeeded(pkg)
9062                && !isRecoverSignatureUpdateNeeded(pkg)) {
9063            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9064            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9065            ArraySet<PublicKey> signingKs;
9066            synchronized (mPackages) {
9067                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9068            }
9069            if (ps.signatures.mSignatures != null
9070                    && ps.signatures.mSignatures.length != 0
9071                    && signingKs != null) {
9072                // Optimization: reuse the existing cached certificates
9073                // if the package appears to be unchanged.
9074                pkg.mSignatures = ps.signatures.mSignatures;
9075                pkg.mSigningKeys = signingKs;
9076                return;
9077            }
9078
9079            Slog.w(TAG, "PackageSetting for " + ps.name
9080                    + " is missing signatures.  Collecting certs again to recover them.");
9081        } else {
9082            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9083        }
9084
9085        try {
9086            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9087            PackageParser.collectCertificates(pkg, policyFlags);
9088        } catch (PackageParserException e) {
9089            throw PackageManagerException.from(e);
9090        } finally {
9091            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9092        }
9093    }
9094
9095    /**
9096     *  Traces a package scan.
9097     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9098     */
9099    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9100            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9101        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9102        try {
9103            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9104        } finally {
9105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9106        }
9107    }
9108
9109    /**
9110     *  Scans a package and returns the newly parsed package.
9111     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9112     */
9113    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9114            long currentTime, UserHandle user) throws PackageManagerException {
9115        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9116        PackageParser pp = new PackageParser();
9117        pp.setSeparateProcesses(mSeparateProcesses);
9118        pp.setOnlyCoreApps(mOnlyCore);
9119        pp.setDisplayMetrics(mMetrics);
9120        pp.setCallback(mPackageParserCallback);
9121
9122        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9123            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9124        }
9125
9126        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9127        final PackageParser.Package pkg;
9128        try {
9129            pkg = pp.parsePackage(scanFile, parseFlags);
9130        } catch (PackageParserException e) {
9131            throw PackageManagerException.from(e);
9132        } finally {
9133            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9134        }
9135
9136        // Static shared libraries have synthetic package names
9137        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9138            renameStaticSharedLibraryPackage(pkg);
9139        }
9140
9141        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9142    }
9143
9144    /**
9145     *  Scans a package and returns the newly parsed package.
9146     *  @throws PackageManagerException on a parse error.
9147     */
9148    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9149            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9150            throws PackageManagerException {
9151        // If the package has children and this is the first dive in the function
9152        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9153        // packages (parent and children) would be successfully scanned before the
9154        // actual scan since scanning mutates internal state and we want to atomically
9155        // install the package and its children.
9156        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9157            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9158                scanFlags |= SCAN_CHECK_ONLY;
9159            }
9160        } else {
9161            scanFlags &= ~SCAN_CHECK_ONLY;
9162        }
9163
9164        // Scan the parent
9165        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9166                scanFlags, currentTime, user);
9167
9168        // Scan the children
9169        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9170        for (int i = 0; i < childCount; i++) {
9171            PackageParser.Package childPackage = pkg.childPackages.get(i);
9172            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9173                    currentTime, user);
9174        }
9175
9176
9177        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9178            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9179        }
9180
9181        return scannedPkg;
9182    }
9183
9184    /**
9185     *  Scans a package and returns the newly parsed package.
9186     *  @throws PackageManagerException on a parse error.
9187     */
9188    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9189            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9190            throws PackageManagerException {
9191        PackageSetting ps = null;
9192        PackageSetting updatedPkg;
9193        // reader
9194        synchronized (mPackages) {
9195            // Look to see if we already know about this package.
9196            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9197            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9198                // This package has been renamed to its original name.  Let's
9199                // use that.
9200                ps = mSettings.getPackageLPr(oldName);
9201            }
9202            // If there was no original package, see one for the real package name.
9203            if (ps == null) {
9204                ps = mSettings.getPackageLPr(pkg.packageName);
9205            }
9206            // Check to see if this package could be hiding/updating a system
9207            // package.  Must look for it either under the original or real
9208            // package name depending on our state.
9209            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9210            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9211
9212            // If this is a package we don't know about on the system partition, we
9213            // may need to remove disabled child packages on the system partition
9214            // or may need to not add child packages if the parent apk is updated
9215            // on the data partition and no longer defines this child package.
9216            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9217                // If this is a parent package for an updated system app and this system
9218                // app got an OTA update which no longer defines some of the child packages
9219                // we have to prune them from the disabled system packages.
9220                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9221                if (disabledPs != null) {
9222                    final int scannedChildCount = (pkg.childPackages != null)
9223                            ? pkg.childPackages.size() : 0;
9224                    final int disabledChildCount = disabledPs.childPackageNames != null
9225                            ? disabledPs.childPackageNames.size() : 0;
9226                    for (int i = 0; i < disabledChildCount; i++) {
9227                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9228                        boolean disabledPackageAvailable = false;
9229                        for (int j = 0; j < scannedChildCount; j++) {
9230                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9231                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9232                                disabledPackageAvailable = true;
9233                                break;
9234                            }
9235                         }
9236                         if (!disabledPackageAvailable) {
9237                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9238                         }
9239                    }
9240                }
9241            }
9242        }
9243
9244        final boolean isUpdatedPkg = updatedPkg != null;
9245        final boolean isUpdatedSystemPkg = isUpdatedPkg
9246                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9247        boolean isUpdatedPkgBetter = false;
9248        // First check if this is a system package that may involve an update
9249        if (isUpdatedSystemPkg) {
9250            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9251            // it needs to drop FLAG_PRIVILEGED.
9252            if (locationIsPrivileged(scanFile)) {
9253                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9254            } else {
9255                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9256            }
9257            // If new package is not located in "/oem" (e.g. due to an OTA),
9258            // it needs to drop FLAG_OEM.
9259            if (locationIsOem(scanFile)) {
9260                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
9261            } else {
9262                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
9263            }
9264
9265            if (ps != null && !ps.codePath.equals(scanFile)) {
9266                // The path has changed from what was last scanned...  check the
9267                // version of the new path against what we have stored to determine
9268                // what to do.
9269                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9270                if (pkg.mVersionCode <= ps.versionCode) {
9271                    // The system package has been updated and the code path does not match
9272                    // Ignore entry. Skip it.
9273                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9274                            + " ignored: updated version " + ps.versionCode
9275                            + " better than this " + pkg.mVersionCode);
9276                    if (!updatedPkg.codePath.equals(scanFile)) {
9277                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9278                                + ps.name + " changing from " + updatedPkg.codePathString
9279                                + " to " + scanFile);
9280                        updatedPkg.codePath = scanFile;
9281                        updatedPkg.codePathString = scanFile.toString();
9282                        updatedPkg.resourcePath = scanFile;
9283                        updatedPkg.resourcePathString = scanFile.toString();
9284                    }
9285                    updatedPkg.pkg = pkg;
9286                    updatedPkg.versionCode = pkg.mVersionCode;
9287
9288                    // Update the disabled system child packages to point to the package too.
9289                    final int childCount = updatedPkg.childPackageNames != null
9290                            ? updatedPkg.childPackageNames.size() : 0;
9291                    for (int i = 0; i < childCount; i++) {
9292                        String childPackageName = updatedPkg.childPackageNames.get(i);
9293                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9294                                childPackageName);
9295                        if (updatedChildPkg != null) {
9296                            updatedChildPkg.pkg = pkg;
9297                            updatedChildPkg.versionCode = pkg.mVersionCode;
9298                        }
9299                    }
9300                } else {
9301                    // The current app on the system partition is better than
9302                    // what we have updated to on the data partition; switch
9303                    // back to the system partition version.
9304                    // At this point, its safely assumed that package installation for
9305                    // apps in system partition will go through. If not there won't be a working
9306                    // version of the app
9307                    // writer
9308                    synchronized (mPackages) {
9309                        // Just remove the loaded entries from package lists.
9310                        mPackages.remove(ps.name);
9311                    }
9312
9313                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9314                            + " reverting from " + ps.codePathString
9315                            + ": new version " + pkg.mVersionCode
9316                            + " better than installed " + ps.versionCode);
9317
9318                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9319                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9320                    synchronized (mInstallLock) {
9321                        args.cleanUpResourcesLI();
9322                    }
9323                    synchronized (mPackages) {
9324                        mSettings.enableSystemPackageLPw(ps.name);
9325                    }
9326                    isUpdatedPkgBetter = true;
9327                }
9328            }
9329        }
9330
9331        String resourcePath = null;
9332        String baseResourcePath = null;
9333        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9334            if (ps != null && ps.resourcePathString != null) {
9335                resourcePath = ps.resourcePathString;
9336                baseResourcePath = ps.resourcePathString;
9337            } else {
9338                // Should not happen at all. Just log an error.
9339                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9340            }
9341        } else {
9342            resourcePath = pkg.codePath;
9343            baseResourcePath = pkg.baseCodePath;
9344        }
9345
9346        // Set application objects path explicitly.
9347        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9348        pkg.setApplicationInfoCodePath(pkg.codePath);
9349        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9350        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9351        pkg.setApplicationInfoResourcePath(resourcePath);
9352        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9353        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9354
9355        // throw an exception if we have an update to a system application, but, it's not more
9356        // recent than the package we've already scanned
9357        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9358            // Set CPU Abis to application info.
9359            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9360                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9361                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9362            } else {
9363                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9364                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9365            }
9366
9367            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9368                    + scanFile + " ignored: updated version " + ps.versionCode
9369                    + " better than this " + pkg.mVersionCode);
9370        }
9371
9372        if (isUpdatedPkg) {
9373            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9374            // initially
9375            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9376
9377            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9378            // flag set initially
9379            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9380                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9381            }
9382
9383            // An updated OEM app will not have the PARSE_IS_OEM
9384            // flag set initially
9385            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9386                policyFlags |= PackageParser.PARSE_IS_OEM;
9387            }
9388        }
9389
9390        // Verify certificates against what was last scanned
9391        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9392
9393        /*
9394         * A new system app appeared, but we already had a non-system one of the
9395         * same name installed earlier.
9396         */
9397        boolean shouldHideSystemApp = false;
9398        if (!isUpdatedPkg && ps != null
9399                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9400            /*
9401             * Check to make sure the signatures match first. If they don't,
9402             * wipe the installed application and its data.
9403             */
9404            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9405                    != PackageManager.SIGNATURE_MATCH) {
9406                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9407                        + " signatures don't match existing userdata copy; removing");
9408                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9409                        "scanPackageInternalLI")) {
9410                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9411                }
9412                ps = null;
9413            } else {
9414                /*
9415                 * If the newly-added system app is an older version than the
9416                 * already installed version, hide it. It will be scanned later
9417                 * and re-added like an update.
9418                 */
9419                if (pkg.mVersionCode <= ps.versionCode) {
9420                    shouldHideSystemApp = true;
9421                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9422                            + " but new version " + pkg.mVersionCode + " better than installed "
9423                            + ps.versionCode + "; hiding system");
9424                } else {
9425                    /*
9426                     * The newly found system app is a newer version that the
9427                     * one previously installed. Simply remove the
9428                     * already-installed application and replace it with our own
9429                     * while keeping the application data.
9430                     */
9431                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9432                            + " reverting from " + ps.codePathString + ": new version "
9433                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9434                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9435                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9436                    synchronized (mInstallLock) {
9437                        args.cleanUpResourcesLI();
9438                    }
9439                }
9440            }
9441        }
9442
9443        // The apk is forward locked (not public) if its code and resources
9444        // are kept in different files. (except for app in either system or
9445        // vendor path).
9446        // TODO grab this value from PackageSettings
9447        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9448            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9449                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9450            }
9451        }
9452
9453        final int userId = ((user == null) ? 0 : user.getIdentifier());
9454        if (ps != null && ps.getInstantApp(userId)) {
9455            scanFlags |= SCAN_AS_INSTANT_APP;
9456        }
9457        if (ps != null && ps.getVirtulalPreload(userId)) {
9458            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9459        }
9460
9461        // Note that we invoke the following method only if we are about to unpack an application
9462        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9463                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9464
9465        /*
9466         * If the system app should be overridden by a previously installed
9467         * data, hide the system app now and let the /data/app scan pick it up
9468         * again.
9469         */
9470        if (shouldHideSystemApp) {
9471            synchronized (mPackages) {
9472                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9473            }
9474        }
9475
9476        return scannedPkg;
9477    }
9478
9479    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9480        // Derive the new package synthetic package name
9481        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9482                + pkg.staticSharedLibVersion);
9483    }
9484
9485    private static String fixProcessName(String defProcessName,
9486            String processName) {
9487        if (processName == null) {
9488            return defProcessName;
9489        }
9490        return processName;
9491    }
9492
9493    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9494            throws PackageManagerException {
9495        if (pkgSetting.signatures.mSignatures != null) {
9496            // Already existing package. Make sure signatures match
9497            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9498                    == PackageManager.SIGNATURE_MATCH;
9499            if (!match) {
9500                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9501                        == PackageManager.SIGNATURE_MATCH;
9502            }
9503            if (!match) {
9504                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9505                        == PackageManager.SIGNATURE_MATCH;
9506            }
9507            if (!match) {
9508                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9509                        + pkg.packageName + " signatures do not match the "
9510                        + "previously installed version; ignoring!");
9511            }
9512        }
9513
9514        // Check for shared user signatures
9515        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9516            // Already existing package. Make sure signatures match
9517            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9518                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9519            if (!match) {
9520                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9521                        == PackageManager.SIGNATURE_MATCH;
9522            }
9523            if (!match) {
9524                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9525                        == PackageManager.SIGNATURE_MATCH;
9526            }
9527            if (!match) {
9528                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9529                        "Package " + pkg.packageName
9530                        + " has no signatures that match those in shared user "
9531                        + pkgSetting.sharedUser.name + "; ignoring!");
9532            }
9533        }
9534    }
9535
9536    /**
9537     * Enforces that only the system UID or root's UID can call a method exposed
9538     * via Binder.
9539     *
9540     * @param message used as message if SecurityException is thrown
9541     * @throws SecurityException if the caller is not system or root
9542     */
9543    private static final void enforceSystemOrRoot(String message) {
9544        final int uid = Binder.getCallingUid();
9545        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9546            throw new SecurityException(message);
9547        }
9548    }
9549
9550    @Override
9551    public void performFstrimIfNeeded() {
9552        enforceSystemOrRoot("Only the system can request fstrim");
9553
9554        // Before everything else, see whether we need to fstrim.
9555        try {
9556            IStorageManager sm = PackageHelper.getStorageManager();
9557            if (sm != null) {
9558                boolean doTrim = false;
9559                final long interval = android.provider.Settings.Global.getLong(
9560                        mContext.getContentResolver(),
9561                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9562                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9563                if (interval > 0) {
9564                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9565                    if (timeSinceLast > interval) {
9566                        doTrim = true;
9567                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9568                                + "; running immediately");
9569                    }
9570                }
9571                if (doTrim) {
9572                    final boolean dexOptDialogShown;
9573                    synchronized (mPackages) {
9574                        dexOptDialogShown = mDexOptDialogShown;
9575                    }
9576                    if (!isFirstBoot() && dexOptDialogShown) {
9577                        try {
9578                            ActivityManager.getService().showBootMessage(
9579                                    mContext.getResources().getString(
9580                                            R.string.android_upgrading_fstrim), true);
9581                        } catch (RemoteException e) {
9582                        }
9583                    }
9584                    sm.runMaintenance();
9585                }
9586            } else {
9587                Slog.e(TAG, "storageManager service unavailable!");
9588            }
9589        } catch (RemoteException e) {
9590            // Can't happen; StorageManagerService is local
9591        }
9592    }
9593
9594    @Override
9595    public void updatePackagesIfNeeded() {
9596        enforceSystemOrRoot("Only the system can request package update");
9597
9598        // We need to re-extract after an OTA.
9599        boolean causeUpgrade = isUpgrade();
9600
9601        // First boot or factory reset.
9602        // Note: we also handle devices that are upgrading to N right now as if it is their
9603        //       first boot, as they do not have profile data.
9604        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9605
9606        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9607        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9608
9609        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9610            return;
9611        }
9612
9613        List<PackageParser.Package> pkgs;
9614        synchronized (mPackages) {
9615            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9616        }
9617
9618        final long startTime = System.nanoTime();
9619        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9620                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9621                    false /* bootComplete */);
9622
9623        final int elapsedTimeSeconds =
9624                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9625
9626        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9627        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9628        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9629        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9630        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9631    }
9632
9633    /*
9634     * Return the prebuilt profile path given a package base code path.
9635     */
9636    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9637        return pkg.baseCodePath + ".prof";
9638    }
9639
9640    /**
9641     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9642     * containing statistics about the invocation. The array consists of three elements,
9643     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9644     * and {@code numberOfPackagesFailed}.
9645     */
9646    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9647            String compilerFilter, boolean bootComplete) {
9648
9649        int numberOfPackagesVisited = 0;
9650        int numberOfPackagesOptimized = 0;
9651        int numberOfPackagesSkipped = 0;
9652        int numberOfPackagesFailed = 0;
9653        final int numberOfPackagesToDexopt = pkgs.size();
9654
9655        for (PackageParser.Package pkg : pkgs) {
9656            numberOfPackagesVisited++;
9657
9658            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9659                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9660                // that are already compiled.
9661                File profileFile = new File(getPrebuildProfilePath(pkg));
9662                // Copy profile if it exists.
9663                if (profileFile.exists()) {
9664                    try {
9665                        // We could also do this lazily before calling dexopt in
9666                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9667                        // is that we don't have a good way to say "do this only once".
9668                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9669                                pkg.applicationInfo.uid, pkg.packageName)) {
9670                            Log.e(TAG, "Installer failed to copy system profile!");
9671                        }
9672                    } catch (Exception e) {
9673                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9674                                e);
9675                    }
9676                }
9677            }
9678
9679            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9680                if (DEBUG_DEXOPT) {
9681                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9682                }
9683                numberOfPackagesSkipped++;
9684                continue;
9685            }
9686
9687            if (DEBUG_DEXOPT) {
9688                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9689                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9690            }
9691
9692            if (showDialog) {
9693                try {
9694                    ActivityManager.getService().showBootMessage(
9695                            mContext.getResources().getString(R.string.android_upgrading_apk,
9696                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9697                } catch (RemoteException e) {
9698                }
9699                synchronized (mPackages) {
9700                    mDexOptDialogShown = true;
9701                }
9702            }
9703
9704            // If the OTA updates a system app which was previously preopted to a non-preopted state
9705            // the app might end up being verified at runtime. That's because by default the apps
9706            // are verify-profile but for preopted apps there's no profile.
9707            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9708            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9709            // filter (by default 'quicken').
9710            // Note that at this stage unused apps are already filtered.
9711            if (isSystemApp(pkg) &&
9712                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9713                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9714                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9715            }
9716
9717            // checkProfiles is false to avoid merging profiles during boot which
9718            // might interfere with background compilation (b/28612421).
9719            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9720            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9721            // trade-off worth doing to save boot time work.
9722            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9723            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9724                    pkg.packageName,
9725                    compilerFilter,
9726                    dexoptFlags));
9727
9728            switch (primaryDexOptStaus) {
9729                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9730                    numberOfPackagesOptimized++;
9731                    break;
9732                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9733                    numberOfPackagesSkipped++;
9734                    break;
9735                case PackageDexOptimizer.DEX_OPT_FAILED:
9736                    numberOfPackagesFailed++;
9737                    break;
9738                default:
9739                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9740                    break;
9741            }
9742        }
9743
9744        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9745                numberOfPackagesFailed };
9746    }
9747
9748    @Override
9749    public void notifyPackageUse(String packageName, int reason) {
9750        synchronized (mPackages) {
9751            final int callingUid = Binder.getCallingUid();
9752            final int callingUserId = UserHandle.getUserId(callingUid);
9753            if (getInstantAppPackageName(callingUid) != null) {
9754                if (!isCallerSameApp(packageName, callingUid)) {
9755                    return;
9756                }
9757            } else {
9758                if (isInstantApp(packageName, callingUserId)) {
9759                    return;
9760                }
9761            }
9762            notifyPackageUseLocked(packageName, reason);
9763        }
9764    }
9765
9766    private void notifyPackageUseLocked(String packageName, int reason) {
9767        final PackageParser.Package p = mPackages.get(packageName);
9768        if (p == null) {
9769            return;
9770        }
9771        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9772    }
9773
9774    @Override
9775    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9776            List<String> classPaths, String loaderIsa) {
9777        int userId = UserHandle.getCallingUserId();
9778        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9779        if (ai == null) {
9780            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9781                + loadingPackageName + ", user=" + userId);
9782            return;
9783        }
9784        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9785    }
9786
9787    @Override
9788    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9789            IDexModuleRegisterCallback callback) {
9790        int userId = UserHandle.getCallingUserId();
9791        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9792        DexManager.RegisterDexModuleResult result;
9793        if (ai == null) {
9794            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9795                     " calling user. package=" + packageName + ", user=" + userId);
9796            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9797        } else {
9798            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9799        }
9800
9801        if (callback != null) {
9802            mHandler.post(() -> {
9803                try {
9804                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9805                } catch (RemoteException e) {
9806                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9807                }
9808            });
9809        }
9810    }
9811
9812    /**
9813     * Ask the package manager to perform a dex-opt with the given compiler filter.
9814     *
9815     * Note: exposed only for the shell command to allow moving packages explicitly to a
9816     *       definite state.
9817     */
9818    @Override
9819    public boolean performDexOptMode(String packageName,
9820            boolean checkProfiles, String targetCompilerFilter, boolean force,
9821            boolean bootComplete, String splitName) {
9822        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9823                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9824                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9825        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9826                splitName, flags));
9827    }
9828
9829    /**
9830     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9831     * secondary dex files belonging to the given package.
9832     *
9833     * Note: exposed only for the shell command to allow moving packages explicitly to a
9834     *       definite state.
9835     */
9836    @Override
9837    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9838            boolean force) {
9839        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9840                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9841                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9842                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9843        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9844    }
9845
9846    /*package*/ boolean performDexOpt(DexoptOptions options) {
9847        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9848            return false;
9849        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9850            return false;
9851        }
9852
9853        if (options.isDexoptOnlySecondaryDex()) {
9854            return mDexManager.dexoptSecondaryDex(options);
9855        } else {
9856            int dexoptStatus = performDexOptWithStatus(options);
9857            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9858        }
9859    }
9860
9861    /**
9862     * Perform dexopt on the given package and return one of following result:
9863     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9864     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9865     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9866     */
9867    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9868        return performDexOptTraced(options);
9869    }
9870
9871    private int performDexOptTraced(DexoptOptions options) {
9872        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9873        try {
9874            return performDexOptInternal(options);
9875        } finally {
9876            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9877        }
9878    }
9879
9880    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9881    // if the package can now be considered up to date for the given filter.
9882    private int performDexOptInternal(DexoptOptions options) {
9883        PackageParser.Package p;
9884        synchronized (mPackages) {
9885            p = mPackages.get(options.getPackageName());
9886            if (p == null) {
9887                // Package could not be found. Report failure.
9888                return PackageDexOptimizer.DEX_OPT_FAILED;
9889            }
9890            mPackageUsage.maybeWriteAsync(mPackages);
9891            mCompilerStats.maybeWriteAsync();
9892        }
9893        long callingId = Binder.clearCallingIdentity();
9894        try {
9895            synchronized (mInstallLock) {
9896                return performDexOptInternalWithDependenciesLI(p, options);
9897            }
9898        } finally {
9899            Binder.restoreCallingIdentity(callingId);
9900        }
9901    }
9902
9903    public ArraySet<String> getOptimizablePackages() {
9904        ArraySet<String> pkgs = new ArraySet<String>();
9905        synchronized (mPackages) {
9906            for (PackageParser.Package p : mPackages.values()) {
9907                if (PackageDexOptimizer.canOptimizePackage(p)) {
9908                    pkgs.add(p.packageName);
9909                }
9910            }
9911        }
9912        return pkgs;
9913    }
9914
9915    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9916            DexoptOptions options) {
9917        // Select the dex optimizer based on the force parameter.
9918        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9919        //       allocate an object here.
9920        PackageDexOptimizer pdo = options.isForce()
9921                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9922                : mPackageDexOptimizer;
9923
9924        // Dexopt all dependencies first. Note: we ignore the return value and march on
9925        // on errors.
9926        // Note that we are going to call performDexOpt on those libraries as many times as
9927        // they are referenced in packages. When we do a batch of performDexOpt (for example
9928        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9929        // and the first package that uses the library will dexopt it. The
9930        // others will see that the compiled code for the library is up to date.
9931        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9932        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9933        if (!deps.isEmpty()) {
9934            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9935                    options.getCompilerFilter(), options.getSplitName(),
9936                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9937            for (PackageParser.Package depPackage : deps) {
9938                // TODO: Analyze and investigate if we (should) profile libraries.
9939                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9940                        getOrCreateCompilerPackageStats(depPackage),
9941                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9942            }
9943        }
9944        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9945                getOrCreateCompilerPackageStats(p),
9946                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9947    }
9948
9949    /**
9950     * Reconcile the information we have about the secondary dex files belonging to
9951     * {@code packagName} and the actual dex files. For all dex files that were
9952     * deleted, update the internal records and delete the generated oat files.
9953     */
9954    @Override
9955    public void reconcileSecondaryDexFiles(String packageName) {
9956        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9957            return;
9958        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9959            return;
9960        }
9961        mDexManager.reconcileSecondaryDexFiles(packageName);
9962    }
9963
9964    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9965    // a reference there.
9966    /*package*/ DexManager getDexManager() {
9967        return mDexManager;
9968    }
9969
9970    /**
9971     * Execute the background dexopt job immediately.
9972     */
9973    @Override
9974    public boolean runBackgroundDexoptJob() {
9975        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9976            return false;
9977        }
9978        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9979    }
9980
9981    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9982        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9983                || p.usesStaticLibraries != null) {
9984            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9985            Set<String> collectedNames = new HashSet<>();
9986            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9987
9988            retValue.remove(p);
9989
9990            return retValue;
9991        } else {
9992            return Collections.emptyList();
9993        }
9994    }
9995
9996    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9997            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9998        if (!collectedNames.contains(p.packageName)) {
9999            collectedNames.add(p.packageName);
10000            collected.add(p);
10001
10002            if (p.usesLibraries != null) {
10003                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10004                        null, collected, collectedNames);
10005            }
10006            if (p.usesOptionalLibraries != null) {
10007                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10008                        null, collected, collectedNames);
10009            }
10010            if (p.usesStaticLibraries != null) {
10011                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10012                        p.usesStaticLibrariesVersions, collected, collectedNames);
10013            }
10014        }
10015    }
10016
10017    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10018            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10019        final int libNameCount = libs.size();
10020        for (int i = 0; i < libNameCount; i++) {
10021            String libName = libs.get(i);
10022            int version = (versions != null && versions.length == libNameCount)
10023                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10024            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10025            if (libPkg != null) {
10026                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10027            }
10028        }
10029    }
10030
10031    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10032        synchronized (mPackages) {
10033            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10034            if (libEntry != null) {
10035                return mPackages.get(libEntry.apk);
10036            }
10037            return null;
10038        }
10039    }
10040
10041    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10042        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10043        if (versionedLib == null) {
10044            return null;
10045        }
10046        return versionedLib.get(version);
10047    }
10048
10049    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10050        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10051                pkg.staticSharedLibName);
10052        if (versionedLib == null) {
10053            return null;
10054        }
10055        int previousLibVersion = -1;
10056        final int versionCount = versionedLib.size();
10057        for (int i = 0; i < versionCount; i++) {
10058            final int libVersion = versionedLib.keyAt(i);
10059            if (libVersion < pkg.staticSharedLibVersion) {
10060                previousLibVersion = Math.max(previousLibVersion, libVersion);
10061            }
10062        }
10063        if (previousLibVersion >= 0) {
10064            return versionedLib.get(previousLibVersion);
10065        }
10066        return null;
10067    }
10068
10069    public void shutdown() {
10070        mPackageUsage.writeNow(mPackages);
10071        mCompilerStats.writeNow();
10072        mDexManager.writePackageDexUsageNow();
10073    }
10074
10075    @Override
10076    public void dumpProfiles(String packageName) {
10077        PackageParser.Package pkg;
10078        synchronized (mPackages) {
10079            pkg = mPackages.get(packageName);
10080            if (pkg == null) {
10081                throw new IllegalArgumentException("Unknown package: " + packageName);
10082            }
10083        }
10084        /* Only the shell, root, or the app user should be able to dump profiles. */
10085        int callingUid = Binder.getCallingUid();
10086        if (callingUid != Process.SHELL_UID &&
10087            callingUid != Process.ROOT_UID &&
10088            callingUid != pkg.applicationInfo.uid) {
10089            throw new SecurityException("dumpProfiles");
10090        }
10091
10092        synchronized (mInstallLock) {
10093            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10094            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10095            try {
10096                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10097                String codePaths = TextUtils.join(";", allCodePaths);
10098                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10099            } catch (InstallerException e) {
10100                Slog.w(TAG, "Failed to dump profiles", e);
10101            }
10102            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10103        }
10104    }
10105
10106    @Override
10107    public void forceDexOpt(String packageName) {
10108        enforceSystemOrRoot("forceDexOpt");
10109
10110        PackageParser.Package pkg;
10111        synchronized (mPackages) {
10112            pkg = mPackages.get(packageName);
10113            if (pkg == null) {
10114                throw new IllegalArgumentException("Unknown package: " + packageName);
10115            }
10116        }
10117
10118        synchronized (mInstallLock) {
10119            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10120
10121            // Whoever is calling forceDexOpt wants a compiled package.
10122            // Don't use profiles since that may cause compilation to be skipped.
10123            final int res = performDexOptInternalWithDependenciesLI(
10124                    pkg,
10125                    new DexoptOptions(packageName,
10126                            getDefaultCompilerFilter(),
10127                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10128
10129            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10130            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10131                throw new IllegalStateException("Failed to dexopt: " + res);
10132            }
10133        }
10134    }
10135
10136    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10137        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10138            Slog.w(TAG, "Unable to update from " + oldPkg.name
10139                    + " to " + newPkg.packageName
10140                    + ": old package not in system partition");
10141            return false;
10142        } else if (mPackages.get(oldPkg.name) != null) {
10143            Slog.w(TAG, "Unable to update from " + oldPkg.name
10144                    + " to " + newPkg.packageName
10145                    + ": old package still exists");
10146            return false;
10147        }
10148        return true;
10149    }
10150
10151    void removeCodePathLI(File codePath) {
10152        if (codePath.isDirectory()) {
10153            try {
10154                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10155            } catch (InstallerException e) {
10156                Slog.w(TAG, "Failed to remove code path", e);
10157            }
10158        } else {
10159            codePath.delete();
10160        }
10161    }
10162
10163    private int[] resolveUserIds(int userId) {
10164        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10165    }
10166
10167    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10168        if (pkg == null) {
10169            Slog.wtf(TAG, "Package was null!", new Throwable());
10170            return;
10171        }
10172        clearAppDataLeafLIF(pkg, userId, flags);
10173        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10174        for (int i = 0; i < childCount; i++) {
10175            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10176        }
10177    }
10178
10179    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10180        final PackageSetting ps;
10181        synchronized (mPackages) {
10182            ps = mSettings.mPackages.get(pkg.packageName);
10183        }
10184        for (int realUserId : resolveUserIds(userId)) {
10185            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10186            try {
10187                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10188                        ceDataInode);
10189            } catch (InstallerException e) {
10190                Slog.w(TAG, String.valueOf(e));
10191            }
10192        }
10193    }
10194
10195    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10196        if (pkg == null) {
10197            Slog.wtf(TAG, "Package was null!", new Throwable());
10198            return;
10199        }
10200        destroyAppDataLeafLIF(pkg, userId, flags);
10201        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10202        for (int i = 0; i < childCount; i++) {
10203            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10204        }
10205    }
10206
10207    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10208        final PackageSetting ps;
10209        synchronized (mPackages) {
10210            ps = mSettings.mPackages.get(pkg.packageName);
10211        }
10212        for (int realUserId : resolveUserIds(userId)) {
10213            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10214            try {
10215                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10216                        ceDataInode);
10217            } catch (InstallerException e) {
10218                Slog.w(TAG, String.valueOf(e));
10219            }
10220            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10221        }
10222    }
10223
10224    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10225        if (pkg == null) {
10226            Slog.wtf(TAG, "Package was null!", new Throwable());
10227            return;
10228        }
10229        destroyAppProfilesLeafLIF(pkg);
10230        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10231        for (int i = 0; i < childCount; i++) {
10232            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10233        }
10234    }
10235
10236    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10237        try {
10238            mInstaller.destroyAppProfiles(pkg.packageName);
10239        } catch (InstallerException e) {
10240            Slog.w(TAG, String.valueOf(e));
10241        }
10242    }
10243
10244    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10245        if (pkg == null) {
10246            Slog.wtf(TAG, "Package was null!", new Throwable());
10247            return;
10248        }
10249        clearAppProfilesLeafLIF(pkg);
10250        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10251        for (int i = 0; i < childCount; i++) {
10252            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10253        }
10254    }
10255
10256    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10257        try {
10258            mInstaller.clearAppProfiles(pkg.packageName);
10259        } catch (InstallerException e) {
10260            Slog.w(TAG, String.valueOf(e));
10261        }
10262    }
10263
10264    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10265            long lastUpdateTime) {
10266        // Set parent install/update time
10267        PackageSetting ps = (PackageSetting) pkg.mExtras;
10268        if (ps != null) {
10269            ps.firstInstallTime = firstInstallTime;
10270            ps.lastUpdateTime = lastUpdateTime;
10271        }
10272        // Set children install/update time
10273        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10274        for (int i = 0; i < childCount; i++) {
10275            PackageParser.Package childPkg = pkg.childPackages.get(i);
10276            ps = (PackageSetting) childPkg.mExtras;
10277            if (ps != null) {
10278                ps.firstInstallTime = firstInstallTime;
10279                ps.lastUpdateTime = lastUpdateTime;
10280            }
10281        }
10282    }
10283
10284    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10285            PackageParser.Package changingLib) {
10286        if (file.path != null) {
10287            usesLibraryFiles.add(file.path);
10288            return;
10289        }
10290        PackageParser.Package p = mPackages.get(file.apk);
10291        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10292            // If we are doing this while in the middle of updating a library apk,
10293            // then we need to make sure to use that new apk for determining the
10294            // dependencies here.  (We haven't yet finished committing the new apk
10295            // to the package manager state.)
10296            if (p == null || p.packageName.equals(changingLib.packageName)) {
10297                p = changingLib;
10298            }
10299        }
10300        if (p != null) {
10301            usesLibraryFiles.addAll(p.getAllCodePaths());
10302            if (p.usesLibraryFiles != null) {
10303                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10304            }
10305        }
10306    }
10307
10308    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10309            PackageParser.Package changingLib) throws PackageManagerException {
10310        if (pkg == null) {
10311            return;
10312        }
10313        ArraySet<String> usesLibraryFiles = null;
10314        if (pkg.usesLibraries != null) {
10315            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10316                    null, null, pkg.packageName, changingLib, true,
10317                    pkg.applicationInfo.targetSdkVersion, null);
10318        }
10319        if (pkg.usesStaticLibraries != null) {
10320            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10321                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10322                    pkg.packageName, changingLib, true,
10323                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10324        }
10325        if (pkg.usesOptionalLibraries != null) {
10326            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10327                    null, null, pkg.packageName, changingLib, false,
10328                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10329        }
10330        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10331            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10332        } else {
10333            pkg.usesLibraryFiles = null;
10334        }
10335    }
10336
10337    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10338            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10339            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10340            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10341            throws PackageManagerException {
10342        final int libCount = requestedLibraries.size();
10343        for (int i = 0; i < libCount; i++) {
10344            final String libName = requestedLibraries.get(i);
10345            final int libVersion = requiredVersions != null ? requiredVersions[i]
10346                    : SharedLibraryInfo.VERSION_UNDEFINED;
10347            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10348            if (libEntry == null) {
10349                if (required) {
10350                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10351                            "Package " + packageName + " requires unavailable shared library "
10352                                    + libName + "; failing!");
10353                } else if (DEBUG_SHARED_LIBRARIES) {
10354                    Slog.i(TAG, "Package " + packageName
10355                            + " desires unavailable shared library "
10356                            + libName + "; ignoring!");
10357                }
10358            } else {
10359                if (requiredVersions != null && requiredCertDigests != null) {
10360                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10361                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10362                            "Package " + packageName + " requires unavailable static shared"
10363                                    + " library " + libName + " version "
10364                                    + libEntry.info.getVersion() + "; failing!");
10365                    }
10366
10367                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10368                    if (libPkg == null) {
10369                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10370                                "Package " + packageName + " requires unavailable static shared"
10371                                        + " library; failing!");
10372                    }
10373
10374                    final String[] expectedCertDigests = requiredCertDigests[i];
10375                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10376                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10377                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10378                            : PackageUtils.computeSignaturesSha256Digests(
10379                                    new Signature[]{libPkg.mSignatures[0]});
10380
10381                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10382                    // target O we don't parse the "additional-certificate" tags similarly
10383                    // how we only consider all certs only for apps targeting O (see above).
10384                    // Therefore, the size check is safe to make.
10385                    if (expectedCertDigests.length != libCertDigests.length) {
10386                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10387                                "Package " + packageName + " requires differently signed" +
10388                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10389                    }
10390
10391                    // Use a predictable order as signature order may vary
10392                    Arrays.sort(libCertDigests);
10393                    Arrays.sort(expectedCertDigests);
10394
10395                    final int certCount = libCertDigests.length;
10396                    for (int j = 0; j < certCount; j++) {
10397                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10398                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10399                                    "Package " + packageName + " requires differently signed" +
10400                                            " static shared library; failing!");
10401                        }
10402                    }
10403                }
10404
10405                if (outUsedLibraries == null) {
10406                    outUsedLibraries = new ArraySet<>();
10407                }
10408                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10409            }
10410        }
10411        return outUsedLibraries;
10412    }
10413
10414    private static boolean hasString(List<String> list, List<String> which) {
10415        if (list == null) {
10416            return false;
10417        }
10418        for (int i=list.size()-1; i>=0; i--) {
10419            for (int j=which.size()-1; j>=0; j--) {
10420                if (which.get(j).equals(list.get(i))) {
10421                    return true;
10422                }
10423            }
10424        }
10425        return false;
10426    }
10427
10428    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10429            PackageParser.Package changingPkg) {
10430        ArrayList<PackageParser.Package> res = null;
10431        for (PackageParser.Package pkg : mPackages.values()) {
10432            if (changingPkg != null
10433                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10434                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10435                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10436                            changingPkg.staticSharedLibName)) {
10437                return null;
10438            }
10439            if (res == null) {
10440                res = new ArrayList<>();
10441            }
10442            res.add(pkg);
10443            try {
10444                updateSharedLibrariesLPr(pkg, changingPkg);
10445            } catch (PackageManagerException e) {
10446                // If a system app update or an app and a required lib missing we
10447                // delete the package and for updated system apps keep the data as
10448                // it is better for the user to reinstall than to be in an limbo
10449                // state. Also libs disappearing under an app should never happen
10450                // - just in case.
10451                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10452                    final int flags = pkg.isUpdatedSystemApp()
10453                            ? PackageManager.DELETE_KEEP_DATA : 0;
10454                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10455                            flags , null, true, null);
10456                }
10457                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10458            }
10459        }
10460        return res;
10461    }
10462
10463    /**
10464     * Derive the value of the {@code cpuAbiOverride} based on the provided
10465     * value and an optional stored value from the package settings.
10466     */
10467    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10468        String cpuAbiOverride = null;
10469
10470        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10471            cpuAbiOverride = null;
10472        } else if (abiOverride != null) {
10473            cpuAbiOverride = abiOverride;
10474        } else if (settings != null) {
10475            cpuAbiOverride = settings.cpuAbiOverrideString;
10476        }
10477
10478        return cpuAbiOverride;
10479    }
10480
10481    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10482            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10483                    throws PackageManagerException {
10484        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10485        // If the package has children and this is the first dive in the function
10486        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10487        // whether all packages (parent and children) would be successfully scanned
10488        // before the actual scan since scanning mutates internal state and we want
10489        // to atomically install the package and its children.
10490        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10491            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10492                scanFlags |= SCAN_CHECK_ONLY;
10493            }
10494        } else {
10495            scanFlags &= ~SCAN_CHECK_ONLY;
10496        }
10497
10498        final PackageParser.Package scannedPkg;
10499        try {
10500            // Scan the parent
10501            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10502            // Scan the children
10503            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10504            for (int i = 0; i < childCount; i++) {
10505                PackageParser.Package childPkg = pkg.childPackages.get(i);
10506                scanPackageLI(childPkg, policyFlags,
10507                        scanFlags, currentTime, user);
10508            }
10509        } finally {
10510            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10511        }
10512
10513        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10514            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10515        }
10516
10517        return scannedPkg;
10518    }
10519
10520    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10521            int scanFlags, long currentTime, @Nullable UserHandle user)
10522                    throws PackageManagerException {
10523        boolean success = false;
10524        try {
10525            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10526                    currentTime, user);
10527            success = true;
10528            return res;
10529        } finally {
10530            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10531                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10532                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10533                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10534                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10535            }
10536        }
10537    }
10538
10539    /**
10540     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10541     */
10542    private static boolean apkHasCode(String fileName) {
10543        StrictJarFile jarFile = null;
10544        try {
10545            jarFile = new StrictJarFile(fileName,
10546                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10547            return jarFile.findEntry("classes.dex") != null;
10548        } catch (IOException ignore) {
10549        } finally {
10550            try {
10551                if (jarFile != null) {
10552                    jarFile.close();
10553                }
10554            } catch (IOException ignore) {}
10555        }
10556        return false;
10557    }
10558
10559    /**
10560     * Enforces code policy for the package. This ensures that if an APK has
10561     * declared hasCode="true" in its manifest that the APK actually contains
10562     * code.
10563     *
10564     * @throws PackageManagerException If bytecode could not be found when it should exist
10565     */
10566    private static void assertCodePolicy(PackageParser.Package pkg)
10567            throws PackageManagerException {
10568        final boolean shouldHaveCode =
10569                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10570        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10571            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10572                    "Package " + pkg.baseCodePath + " code is missing");
10573        }
10574
10575        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10576            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10577                final boolean splitShouldHaveCode =
10578                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10579                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10580                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10581                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10582                }
10583            }
10584        }
10585    }
10586
10587    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10588            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10589                    throws PackageManagerException {
10590        if (DEBUG_PACKAGE_SCANNING) {
10591            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10592                Log.d(TAG, "Scanning package " + pkg.packageName);
10593        }
10594
10595        applyPolicy(pkg, policyFlags);
10596
10597        assertPackageIsValid(pkg, policyFlags, scanFlags);
10598
10599        if (Build.IS_DEBUGGABLE &&
10600                pkg.isPrivilegedApp() &&
10601                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10602            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10603        }
10604
10605        // Initialize package source and resource directories
10606        final File scanFile = new File(pkg.codePath);
10607        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10608        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10609
10610        SharedUserSetting suid = null;
10611        PackageSetting pkgSetting = null;
10612
10613        // Getting the package setting may have a side-effect, so if we
10614        // are only checking if scan would succeed, stash a copy of the
10615        // old setting to restore at the end.
10616        PackageSetting nonMutatedPs = null;
10617
10618        // We keep references to the derived CPU Abis from settings in oder to reuse
10619        // them in the case where we're not upgrading or booting for the first time.
10620        String primaryCpuAbiFromSettings = null;
10621        String secondaryCpuAbiFromSettings = null;
10622
10623        // writer
10624        synchronized (mPackages) {
10625            if (pkg.mSharedUserId != null) {
10626                // SIDE EFFECTS; may potentially allocate a new shared user
10627                suid = mSettings.getSharedUserLPw(
10628                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10629                if (DEBUG_PACKAGE_SCANNING) {
10630                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10631                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10632                                + "): packages=" + suid.packages);
10633                }
10634            }
10635
10636            // Check if we are renaming from an original package name.
10637            PackageSetting origPackage = null;
10638            String realName = null;
10639            if (pkg.mOriginalPackages != null) {
10640                // This package may need to be renamed to a previously
10641                // installed name.  Let's check on that...
10642                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10643                if (pkg.mOriginalPackages.contains(renamed)) {
10644                    // This package had originally been installed as the
10645                    // original name, and we have already taken care of
10646                    // transitioning to the new one.  Just update the new
10647                    // one to continue using the old name.
10648                    realName = pkg.mRealPackage;
10649                    if (!pkg.packageName.equals(renamed)) {
10650                        // Callers into this function may have already taken
10651                        // care of renaming the package; only do it here if
10652                        // it is not already done.
10653                        pkg.setPackageName(renamed);
10654                    }
10655                } else {
10656                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10657                        if ((origPackage = mSettings.getPackageLPr(
10658                                pkg.mOriginalPackages.get(i))) != null) {
10659                            // We do have the package already installed under its
10660                            // original name...  should we use it?
10661                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10662                                // New package is not compatible with original.
10663                                origPackage = null;
10664                                continue;
10665                            } else if (origPackage.sharedUser != null) {
10666                                // Make sure uid is compatible between packages.
10667                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10668                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10669                                            + " to " + pkg.packageName + ": old uid "
10670                                            + origPackage.sharedUser.name
10671                                            + " differs from " + pkg.mSharedUserId);
10672                                    origPackage = null;
10673                                    continue;
10674                                }
10675                                // TODO: Add case when shared user id is added [b/28144775]
10676                            } else {
10677                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10678                                        + pkg.packageName + " to old name " + origPackage.name);
10679                            }
10680                            break;
10681                        }
10682                    }
10683                }
10684            }
10685
10686            if (mTransferedPackages.contains(pkg.packageName)) {
10687                Slog.w(TAG, "Package " + pkg.packageName
10688                        + " was transferred to another, but its .apk remains");
10689            }
10690
10691            // See comments in nonMutatedPs declaration
10692            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10693                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10694                if (foundPs != null) {
10695                    nonMutatedPs = new PackageSetting(foundPs);
10696                }
10697            }
10698
10699            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10700                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10701                if (foundPs != null) {
10702                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10703                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10704                }
10705            }
10706
10707            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10708            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10709                PackageManagerService.reportSettingsProblem(Log.WARN,
10710                        "Package " + pkg.packageName + " shared user changed from "
10711                                + (pkgSetting.sharedUser != null
10712                                        ? pkgSetting.sharedUser.name : "<nothing>")
10713                                + " to "
10714                                + (suid != null ? suid.name : "<nothing>")
10715                                + "; replacing with new");
10716                pkgSetting = null;
10717            }
10718            final PackageSetting oldPkgSetting =
10719                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10720            final PackageSetting disabledPkgSetting =
10721                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10722
10723            String[] usesStaticLibraries = null;
10724            if (pkg.usesStaticLibraries != null) {
10725                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10726                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10727            }
10728
10729            if (pkgSetting == null) {
10730                final String parentPackageName = (pkg.parentPackage != null)
10731                        ? pkg.parentPackage.packageName : null;
10732                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10733                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10734                // REMOVE SharedUserSetting from method; update in a separate call
10735                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10736                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10737                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10738                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10739                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10740                        true /*allowInstall*/, instantApp, virtualPreload,
10741                        parentPackageName, pkg.getChildPackageNames(),
10742                        UserManagerService.getInstance(), usesStaticLibraries,
10743                        pkg.usesStaticLibrariesVersions);
10744                // SIDE EFFECTS; updates system state; move elsewhere
10745                if (origPackage != null) {
10746                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10747                }
10748                mSettings.addUserToSettingLPw(pkgSetting);
10749            } else {
10750                // REMOVE SharedUserSetting from method; update in a separate call.
10751                //
10752                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10753                // secondaryCpuAbi are not known at this point so we always update them
10754                // to null here, only to reset them at a later point.
10755                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10756                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10757                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10758                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10759                        UserManagerService.getInstance(), usesStaticLibraries,
10760                        pkg.usesStaticLibrariesVersions);
10761            }
10762            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10763            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10764
10765            // SIDE EFFECTS; modifies system state; move elsewhere
10766            if (pkgSetting.origPackage != null) {
10767                // If we are first transitioning from an original package,
10768                // fix up the new package's name now.  We need to do this after
10769                // looking up the package under its new name, so getPackageLP
10770                // can take care of fiddling things correctly.
10771                pkg.setPackageName(origPackage.name);
10772
10773                // File a report about this.
10774                String msg = "New package " + pkgSetting.realName
10775                        + " renamed to replace old package " + pkgSetting.name;
10776                reportSettingsProblem(Log.WARN, msg);
10777
10778                // Make a note of it.
10779                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10780                    mTransferedPackages.add(origPackage.name);
10781                }
10782
10783                // No longer need to retain this.
10784                pkgSetting.origPackage = null;
10785            }
10786
10787            // SIDE EFFECTS; modifies system state; move elsewhere
10788            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10789                // Make a note of it.
10790                mTransferedPackages.add(pkg.packageName);
10791            }
10792
10793            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10794                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10795            }
10796
10797            if ((scanFlags & SCAN_BOOTING) == 0
10798                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10799                // Check all shared libraries and map to their actual file path.
10800                // We only do this here for apps not on a system dir, because those
10801                // are the only ones that can fail an install due to this.  We
10802                // will take care of the system apps by updating all of their
10803                // library paths after the scan is done. Also during the initial
10804                // scan don't update any libs as we do this wholesale after all
10805                // apps are scanned to avoid dependency based scanning.
10806                updateSharedLibrariesLPr(pkg, null);
10807            }
10808
10809            if (mFoundPolicyFile) {
10810                SELinuxMMAC.assignSeInfoValue(pkg);
10811            }
10812            pkg.applicationInfo.uid = pkgSetting.appId;
10813            pkg.mExtras = pkgSetting;
10814
10815
10816            // Static shared libs have same package with different versions where
10817            // we internally use a synthetic package name to allow multiple versions
10818            // of the same package, therefore we need to compare signatures against
10819            // the package setting for the latest library version.
10820            PackageSetting signatureCheckPs = pkgSetting;
10821            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10822                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10823                if (libraryEntry != null) {
10824                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10825                }
10826            }
10827
10828            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10829                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10830                    // We just determined the app is signed correctly, so bring
10831                    // over the latest parsed certs.
10832                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10833                } else {
10834                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10835                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10836                                "Package " + pkg.packageName + " upgrade keys do not match the "
10837                                + "previously installed version");
10838                    } else {
10839                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10840                        String msg = "System package " + pkg.packageName
10841                                + " signature changed; retaining data.";
10842                        reportSettingsProblem(Log.WARN, msg);
10843                    }
10844                }
10845            } else {
10846                try {
10847                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10848                    verifySignaturesLP(signatureCheckPs, pkg);
10849                    // We just determined the app is signed correctly, so bring
10850                    // over the latest parsed certs.
10851                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10852                } catch (PackageManagerException e) {
10853                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10854                        throw e;
10855                    }
10856                    // The signature has changed, but this package is in the system
10857                    // image...  let's recover!
10858                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10859                    // However...  if this package is part of a shared user, but it
10860                    // doesn't match the signature of the shared user, let's fail.
10861                    // What this means is that you can't change the signatures
10862                    // associated with an overall shared user, which doesn't seem all
10863                    // that unreasonable.
10864                    if (signatureCheckPs.sharedUser != null) {
10865                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10866                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10867                            throw new PackageManagerException(
10868                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10869                                    "Signature mismatch for shared user: "
10870                                            + pkgSetting.sharedUser);
10871                        }
10872                    }
10873                    // File a report about this.
10874                    String msg = "System package " + pkg.packageName
10875                            + " signature changed; retaining data.";
10876                    reportSettingsProblem(Log.WARN, msg);
10877                }
10878            }
10879
10880            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10881                // This package wants to adopt ownership of permissions from
10882                // another package.
10883                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10884                    final String origName = pkg.mAdoptPermissions.get(i);
10885                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10886                    if (orig != null) {
10887                        if (verifyPackageUpdateLPr(orig, pkg)) {
10888                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10889                                    + pkg.packageName);
10890                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10891                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10892                        }
10893                    }
10894                }
10895            }
10896        }
10897
10898        pkg.applicationInfo.processName = fixProcessName(
10899                pkg.applicationInfo.packageName,
10900                pkg.applicationInfo.processName);
10901
10902        if (pkg != mPlatformPackage) {
10903            // Get all of our default paths setup
10904            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10905        }
10906
10907        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10908
10909        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10910            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10911                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10912                final boolean extractNativeLibs = !pkg.isLibrary();
10913                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10914                        mAppLib32InstallDir);
10915                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10916
10917                // Some system apps still use directory structure for native libraries
10918                // in which case we might end up not detecting abi solely based on apk
10919                // structure. Try to detect abi based on directory structure.
10920                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10921                        pkg.applicationInfo.primaryCpuAbi == null) {
10922                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10923                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10924                }
10925            } else {
10926                // This is not a first boot or an upgrade, don't bother deriving the
10927                // ABI during the scan. Instead, trust the value that was stored in the
10928                // package setting.
10929                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10930                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10931
10932                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10933
10934                if (DEBUG_ABI_SELECTION) {
10935                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10936                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10937                        pkg.applicationInfo.secondaryCpuAbi);
10938                }
10939            }
10940        } else {
10941            if ((scanFlags & SCAN_MOVE) != 0) {
10942                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10943                // but we already have this packages package info in the PackageSetting. We just
10944                // use that and derive the native library path based on the new codepath.
10945                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10946                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10947            }
10948
10949            // Set native library paths again. For moves, the path will be updated based on the
10950            // ABIs we've determined above. For non-moves, the path will be updated based on the
10951            // ABIs we determined during compilation, but the path will depend on the final
10952            // package path (after the rename away from the stage path).
10953            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10954        }
10955
10956        // This is a special case for the "system" package, where the ABI is
10957        // dictated by the zygote configuration (and init.rc). We should keep track
10958        // of this ABI so that we can deal with "normal" applications that run under
10959        // the same UID correctly.
10960        if (mPlatformPackage == pkg) {
10961            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10962                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10963        }
10964
10965        // If there's a mismatch between the abi-override in the package setting
10966        // and the abiOverride specified for the install. Warn about this because we
10967        // would've already compiled the app without taking the package setting into
10968        // account.
10969        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10970            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10971                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10972                        " for package " + pkg.packageName);
10973            }
10974        }
10975
10976        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10977        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10978        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10979
10980        // Copy the derived override back to the parsed package, so that we can
10981        // update the package settings accordingly.
10982        pkg.cpuAbiOverride = cpuAbiOverride;
10983
10984        if (DEBUG_ABI_SELECTION) {
10985            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10986                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10987                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10988        }
10989
10990        // Push the derived path down into PackageSettings so we know what to
10991        // clean up at uninstall time.
10992        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10993
10994        if (DEBUG_ABI_SELECTION) {
10995            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10996                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10997                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10998        }
10999
11000        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11001        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11002            // We don't do this here during boot because we can do it all
11003            // at once after scanning all existing packages.
11004            //
11005            // We also do this *before* we perform dexopt on this package, so that
11006            // we can avoid redundant dexopts, and also to make sure we've got the
11007            // code and package path correct.
11008            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11009        }
11010
11011        if (mFactoryTest && pkg.requestedPermissions.contains(
11012                android.Manifest.permission.FACTORY_TEST)) {
11013            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11014        }
11015
11016        if (isSystemApp(pkg)) {
11017            pkgSetting.isOrphaned = true;
11018        }
11019
11020        // Take care of first install / last update times.
11021        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11022        if (currentTime != 0) {
11023            if (pkgSetting.firstInstallTime == 0) {
11024                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11025            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11026                pkgSetting.lastUpdateTime = currentTime;
11027            }
11028        } else if (pkgSetting.firstInstallTime == 0) {
11029            // We need *something*.  Take time time stamp of the file.
11030            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11031        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11032            if (scanFileTime != pkgSetting.timeStamp) {
11033                // A package on the system image has changed; consider this
11034                // to be an update.
11035                pkgSetting.lastUpdateTime = scanFileTime;
11036            }
11037        }
11038        pkgSetting.setTimeStamp(scanFileTime);
11039
11040        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11041            if (nonMutatedPs != null) {
11042                synchronized (mPackages) {
11043                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11044                }
11045            }
11046        } else {
11047            final int userId = user == null ? 0 : user.getIdentifier();
11048            // Modify state for the given package setting
11049            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11050                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11051            if (pkgSetting.getInstantApp(userId)) {
11052                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11053            }
11054        }
11055        return pkg;
11056    }
11057
11058    /**
11059     * Applies policy to the parsed package based upon the given policy flags.
11060     * Ensures the package is in a good state.
11061     * <p>
11062     * Implementation detail: This method must NOT have any side effect. It would
11063     * ideally be static, but, it requires locks to read system state.
11064     */
11065    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11066        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11067            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11068            if (pkg.applicationInfo.isDirectBootAware()) {
11069                // we're direct boot aware; set for all components
11070                for (PackageParser.Service s : pkg.services) {
11071                    s.info.encryptionAware = s.info.directBootAware = true;
11072                }
11073                for (PackageParser.Provider p : pkg.providers) {
11074                    p.info.encryptionAware = p.info.directBootAware = true;
11075                }
11076                for (PackageParser.Activity a : pkg.activities) {
11077                    a.info.encryptionAware = a.info.directBootAware = true;
11078                }
11079                for (PackageParser.Activity r : pkg.receivers) {
11080                    r.info.encryptionAware = r.info.directBootAware = true;
11081                }
11082            }
11083            if (compressedFileExists(pkg.codePath)) {
11084                pkg.isStub = true;
11085            }
11086        } else {
11087            // Only allow system apps to be flagged as core apps.
11088            pkg.coreApp = false;
11089            // clear flags not applicable to regular apps
11090            pkg.applicationInfo.privateFlags &=
11091                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11092            pkg.applicationInfo.privateFlags &=
11093                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11094        }
11095        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11096
11097        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11098            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11099        }
11100
11101        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
11102            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
11103        }
11104
11105        if (!isSystemApp(pkg)) {
11106            // Only system apps can use these features.
11107            pkg.mOriginalPackages = null;
11108            pkg.mRealPackage = null;
11109            pkg.mAdoptPermissions = null;
11110        }
11111    }
11112
11113    /**
11114     * Asserts the parsed package is valid according to the given policy. If the
11115     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11116     * <p>
11117     * Implementation detail: This method must NOT have any side effects. It would
11118     * ideally be static, but, it requires locks to read system state.
11119     *
11120     * @throws PackageManagerException If the package fails any of the validation checks
11121     */
11122    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11123            throws PackageManagerException {
11124        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11125            assertCodePolicy(pkg);
11126        }
11127
11128        if (pkg.applicationInfo.getCodePath() == null ||
11129                pkg.applicationInfo.getResourcePath() == null) {
11130            // Bail out. The resource and code paths haven't been set.
11131            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11132                    "Code and resource paths haven't been set correctly");
11133        }
11134
11135        // Make sure we're not adding any bogus keyset info
11136        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11137        ksms.assertScannedPackageValid(pkg);
11138
11139        synchronized (mPackages) {
11140            // The special "android" package can only be defined once
11141            if (pkg.packageName.equals("android")) {
11142                if (mAndroidApplication != null) {
11143                    Slog.w(TAG, "*************************************************");
11144                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11145                    Slog.w(TAG, " codePath=" + pkg.codePath);
11146                    Slog.w(TAG, "*************************************************");
11147                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11148                            "Core android package being redefined.  Skipping.");
11149                }
11150            }
11151
11152            // A package name must be unique; don't allow duplicates
11153            if (mPackages.containsKey(pkg.packageName)) {
11154                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11155                        "Application package " + pkg.packageName
11156                        + " already installed.  Skipping duplicate.");
11157            }
11158
11159            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11160                // Static libs have a synthetic package name containing the version
11161                // but we still want the base name to be unique.
11162                if (mPackages.containsKey(pkg.manifestPackageName)) {
11163                    throw new PackageManagerException(
11164                            "Duplicate static shared lib provider package");
11165                }
11166
11167                // Static shared libraries should have at least O target SDK
11168                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11169                    throw new PackageManagerException(
11170                            "Packages declaring static-shared libs must target O SDK or higher");
11171                }
11172
11173                // Package declaring static a shared lib cannot be instant apps
11174                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11175                    throw new PackageManagerException(
11176                            "Packages declaring static-shared libs cannot be instant apps");
11177                }
11178
11179                // Package declaring static a shared lib cannot be renamed since the package
11180                // name is synthetic and apps can't code around package manager internals.
11181                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11182                    throw new PackageManagerException(
11183                            "Packages declaring static-shared libs cannot be renamed");
11184                }
11185
11186                // Package declaring static a shared lib cannot declare child packages
11187                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11188                    throw new PackageManagerException(
11189                            "Packages declaring static-shared libs cannot have child packages");
11190                }
11191
11192                // Package declaring static a shared lib cannot declare dynamic libs
11193                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11194                    throw new PackageManagerException(
11195                            "Packages declaring static-shared libs cannot declare dynamic libs");
11196                }
11197
11198                // Package declaring static a shared lib cannot declare shared users
11199                if (pkg.mSharedUserId != null) {
11200                    throw new PackageManagerException(
11201                            "Packages declaring static-shared libs cannot declare shared users");
11202                }
11203
11204                // Static shared libs cannot declare activities
11205                if (!pkg.activities.isEmpty()) {
11206                    throw new PackageManagerException(
11207                            "Static shared libs cannot declare activities");
11208                }
11209
11210                // Static shared libs cannot declare services
11211                if (!pkg.services.isEmpty()) {
11212                    throw new PackageManagerException(
11213                            "Static shared libs cannot declare services");
11214                }
11215
11216                // Static shared libs cannot declare providers
11217                if (!pkg.providers.isEmpty()) {
11218                    throw new PackageManagerException(
11219                            "Static shared libs cannot declare content providers");
11220                }
11221
11222                // Static shared libs cannot declare receivers
11223                if (!pkg.receivers.isEmpty()) {
11224                    throw new PackageManagerException(
11225                            "Static shared libs cannot declare broadcast receivers");
11226                }
11227
11228                // Static shared libs cannot declare permission groups
11229                if (!pkg.permissionGroups.isEmpty()) {
11230                    throw new PackageManagerException(
11231                            "Static shared libs cannot declare permission groups");
11232                }
11233
11234                // Static shared libs cannot declare permissions
11235                if (!pkg.permissions.isEmpty()) {
11236                    throw new PackageManagerException(
11237                            "Static shared libs cannot declare permissions");
11238                }
11239
11240                // Static shared libs cannot declare protected broadcasts
11241                if (pkg.protectedBroadcasts != null) {
11242                    throw new PackageManagerException(
11243                            "Static shared libs cannot declare protected broadcasts");
11244                }
11245
11246                // Static shared libs cannot be overlay targets
11247                if (pkg.mOverlayTarget != null) {
11248                    throw new PackageManagerException(
11249                            "Static shared libs cannot be overlay targets");
11250                }
11251
11252                // The version codes must be ordered as lib versions
11253                int minVersionCode = Integer.MIN_VALUE;
11254                int maxVersionCode = Integer.MAX_VALUE;
11255
11256                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11257                        pkg.staticSharedLibName);
11258                if (versionedLib != null) {
11259                    final int versionCount = versionedLib.size();
11260                    for (int i = 0; i < versionCount; i++) {
11261                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11262                        final int libVersionCode = libInfo.getDeclaringPackage()
11263                                .getVersionCode();
11264                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11265                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11266                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11267                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11268                        } else {
11269                            minVersionCode = maxVersionCode = libVersionCode;
11270                            break;
11271                        }
11272                    }
11273                }
11274                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11275                    throw new PackageManagerException("Static shared"
11276                            + " lib version codes must be ordered as lib versions");
11277                }
11278            }
11279
11280            // Only privileged apps and updated privileged apps can add child packages.
11281            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11282                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11283                    throw new PackageManagerException("Only privileged apps can add child "
11284                            + "packages. Ignoring package " + pkg.packageName);
11285                }
11286                final int childCount = pkg.childPackages.size();
11287                for (int i = 0; i < childCount; i++) {
11288                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11289                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11290                            childPkg.packageName)) {
11291                        throw new PackageManagerException("Can't override child of "
11292                                + "another disabled app. Ignoring package " + pkg.packageName);
11293                    }
11294                }
11295            }
11296
11297            // If we're only installing presumed-existing packages, require that the
11298            // scanned APK is both already known and at the path previously established
11299            // for it.  Previously unknown packages we pick up normally, but if we have an
11300            // a priori expectation about this package's install presence, enforce it.
11301            // With a singular exception for new system packages. When an OTA contains
11302            // a new system package, we allow the codepath to change from a system location
11303            // to the user-installed location. If we don't allow this change, any newer,
11304            // user-installed version of the application will be ignored.
11305            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11306                if (mExpectingBetter.containsKey(pkg.packageName)) {
11307                    logCriticalInfo(Log.WARN,
11308                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11309                } else {
11310                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11311                    if (known != null) {
11312                        if (DEBUG_PACKAGE_SCANNING) {
11313                            Log.d(TAG, "Examining " + pkg.codePath
11314                                    + " and requiring known paths " + known.codePathString
11315                                    + " & " + known.resourcePathString);
11316                        }
11317                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11318                                || !pkg.applicationInfo.getResourcePath().equals(
11319                                        known.resourcePathString)) {
11320                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11321                                    "Application package " + pkg.packageName
11322                                    + " found at " + pkg.applicationInfo.getCodePath()
11323                                    + " but expected at " + known.codePathString
11324                                    + "; ignoring.");
11325                        }
11326                    } else {
11327                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11328                                "Application package " + pkg.packageName
11329                                + " not found; ignoring.");
11330                    }
11331                }
11332            }
11333
11334            // Verify that this new package doesn't have any content providers
11335            // that conflict with existing packages.  Only do this if the
11336            // package isn't already installed, since we don't want to break
11337            // things that are installed.
11338            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11339                final int N = pkg.providers.size();
11340                int i;
11341                for (i=0; i<N; i++) {
11342                    PackageParser.Provider p = pkg.providers.get(i);
11343                    if (p.info.authority != null) {
11344                        String names[] = p.info.authority.split(";");
11345                        for (int j = 0; j < names.length; j++) {
11346                            if (mProvidersByAuthority.containsKey(names[j])) {
11347                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11348                                final String otherPackageName =
11349                                        ((other != null && other.getComponentName() != null) ?
11350                                                other.getComponentName().getPackageName() : "?");
11351                                throw new PackageManagerException(
11352                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11353                                        "Can't install because provider name " + names[j]
11354                                                + " (in package " + pkg.applicationInfo.packageName
11355                                                + ") is already used by " + otherPackageName);
11356                            }
11357                        }
11358                    }
11359                }
11360            }
11361        }
11362    }
11363
11364    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11365            int type, String declaringPackageName, int declaringVersionCode) {
11366        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11367        if (versionedLib == null) {
11368            versionedLib = new SparseArray<>();
11369            mSharedLibraries.put(name, versionedLib);
11370            if (type == SharedLibraryInfo.TYPE_STATIC) {
11371                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11372            }
11373        } else if (versionedLib.indexOfKey(version) >= 0) {
11374            return false;
11375        }
11376        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11377                version, type, declaringPackageName, declaringVersionCode);
11378        versionedLib.put(version, libEntry);
11379        return true;
11380    }
11381
11382    private boolean removeSharedLibraryLPw(String name, int version) {
11383        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11384        if (versionedLib == null) {
11385            return false;
11386        }
11387        final int libIdx = versionedLib.indexOfKey(version);
11388        if (libIdx < 0) {
11389            return false;
11390        }
11391        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11392        versionedLib.remove(version);
11393        if (versionedLib.size() <= 0) {
11394            mSharedLibraries.remove(name);
11395            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11396                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11397                        .getPackageName());
11398            }
11399        }
11400        return true;
11401    }
11402
11403    /**
11404     * Adds a scanned package to the system. When this method is finished, the package will
11405     * be available for query, resolution, etc...
11406     */
11407    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11408            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11409        final String pkgName = pkg.packageName;
11410        if (mCustomResolverComponentName != null &&
11411                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11412            setUpCustomResolverActivity(pkg);
11413        }
11414
11415        if (pkg.packageName.equals("android")) {
11416            synchronized (mPackages) {
11417                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11418                    // Set up information for our fall-back user intent resolution activity.
11419                    mPlatformPackage = pkg;
11420                    pkg.mVersionCode = mSdkVersion;
11421                    mAndroidApplication = pkg.applicationInfo;
11422                    if (!mResolverReplaced) {
11423                        mResolveActivity.applicationInfo = mAndroidApplication;
11424                        mResolveActivity.name = ResolverActivity.class.getName();
11425                        mResolveActivity.packageName = mAndroidApplication.packageName;
11426                        mResolveActivity.processName = "system:ui";
11427                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11428                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11429                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11430                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11431                        mResolveActivity.exported = true;
11432                        mResolveActivity.enabled = true;
11433                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11434                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11435                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11436                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11437                                | ActivityInfo.CONFIG_ORIENTATION
11438                                | ActivityInfo.CONFIG_KEYBOARD
11439                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11440                        mResolveInfo.activityInfo = mResolveActivity;
11441                        mResolveInfo.priority = 0;
11442                        mResolveInfo.preferredOrder = 0;
11443                        mResolveInfo.match = 0;
11444                        mResolveComponentName = new ComponentName(
11445                                mAndroidApplication.packageName, mResolveActivity.name);
11446                    }
11447                }
11448            }
11449        }
11450
11451        ArrayList<PackageParser.Package> clientLibPkgs = null;
11452        // writer
11453        synchronized (mPackages) {
11454            boolean hasStaticSharedLibs = false;
11455
11456            // Any app can add new static shared libraries
11457            if (pkg.staticSharedLibName != null) {
11458                // Static shared libs don't allow renaming as they have synthetic package
11459                // names to allow install of multiple versions, so use name from manifest.
11460                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11461                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11462                        pkg.manifestPackageName, pkg.mVersionCode)) {
11463                    hasStaticSharedLibs = true;
11464                } else {
11465                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11466                                + pkg.staticSharedLibName + " already exists; skipping");
11467                }
11468                // Static shared libs cannot be updated once installed since they
11469                // use synthetic package name which includes the version code, so
11470                // not need to update other packages's shared lib dependencies.
11471            }
11472
11473            if (!hasStaticSharedLibs
11474                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11475                // Only system apps can add new dynamic shared libraries.
11476                if (pkg.libraryNames != null) {
11477                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11478                        String name = pkg.libraryNames.get(i);
11479                        boolean allowed = false;
11480                        if (pkg.isUpdatedSystemApp()) {
11481                            // New library entries can only be added through the
11482                            // system image.  This is important to get rid of a lot
11483                            // of nasty edge cases: for example if we allowed a non-
11484                            // system update of the app to add a library, then uninstalling
11485                            // the update would make the library go away, and assumptions
11486                            // we made such as through app install filtering would now
11487                            // have allowed apps on the device which aren't compatible
11488                            // with it.  Better to just have the restriction here, be
11489                            // conservative, and create many fewer cases that can negatively
11490                            // impact the user experience.
11491                            final PackageSetting sysPs = mSettings
11492                                    .getDisabledSystemPkgLPr(pkg.packageName);
11493                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11494                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11495                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11496                                        allowed = true;
11497                                        break;
11498                                    }
11499                                }
11500                            }
11501                        } else {
11502                            allowed = true;
11503                        }
11504                        if (allowed) {
11505                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11506                                    SharedLibraryInfo.VERSION_UNDEFINED,
11507                                    SharedLibraryInfo.TYPE_DYNAMIC,
11508                                    pkg.packageName, pkg.mVersionCode)) {
11509                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11510                                        + name + " already exists; skipping");
11511                            }
11512                        } else {
11513                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11514                                    + name + " that is not declared on system image; skipping");
11515                        }
11516                    }
11517
11518                    if ((scanFlags & SCAN_BOOTING) == 0) {
11519                        // If we are not booting, we need to update any applications
11520                        // that are clients of our shared library.  If we are booting,
11521                        // this will all be done once the scan is complete.
11522                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11523                    }
11524                }
11525            }
11526        }
11527
11528        if ((scanFlags & SCAN_BOOTING) != 0) {
11529            // No apps can run during boot scan, so they don't need to be frozen
11530        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11531            // Caller asked to not kill app, so it's probably not frozen
11532        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11533            // Caller asked us to ignore frozen check for some reason; they
11534            // probably didn't know the package name
11535        } else {
11536            // We're doing major surgery on this package, so it better be frozen
11537            // right now to keep it from launching
11538            checkPackageFrozen(pkgName);
11539        }
11540
11541        // Also need to kill any apps that are dependent on the library.
11542        if (clientLibPkgs != null) {
11543            for (int i=0; i<clientLibPkgs.size(); i++) {
11544                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11545                killApplication(clientPkg.applicationInfo.packageName,
11546                        clientPkg.applicationInfo.uid, "update lib");
11547            }
11548        }
11549
11550        // writer
11551        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11552
11553        synchronized (mPackages) {
11554            // We don't expect installation to fail beyond this point
11555
11556            // Add the new setting to mSettings
11557            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11558            // Add the new setting to mPackages
11559            mPackages.put(pkg.applicationInfo.packageName, pkg);
11560            // Make sure we don't accidentally delete its data.
11561            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11562            while (iter.hasNext()) {
11563                PackageCleanItem item = iter.next();
11564                if (pkgName.equals(item.packageName)) {
11565                    iter.remove();
11566                }
11567            }
11568
11569            // Add the package's KeySets to the global KeySetManagerService
11570            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11571            ksms.addScannedPackageLPw(pkg);
11572
11573            int N = pkg.providers.size();
11574            StringBuilder r = null;
11575            int i;
11576            for (i=0; i<N; i++) {
11577                PackageParser.Provider p = pkg.providers.get(i);
11578                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11579                        p.info.processName);
11580                mProviders.addProvider(p);
11581                p.syncable = p.info.isSyncable;
11582                if (p.info.authority != null) {
11583                    String names[] = p.info.authority.split(";");
11584                    p.info.authority = null;
11585                    for (int j = 0; j < names.length; j++) {
11586                        if (j == 1 && p.syncable) {
11587                            // We only want the first authority for a provider to possibly be
11588                            // syncable, so if we already added this provider using a different
11589                            // authority clear the syncable flag. We copy the provider before
11590                            // changing it because the mProviders object contains a reference
11591                            // to a provider that we don't want to change.
11592                            // Only do this for the second authority since the resulting provider
11593                            // object can be the same for all future authorities for this provider.
11594                            p = new PackageParser.Provider(p);
11595                            p.syncable = false;
11596                        }
11597                        if (!mProvidersByAuthority.containsKey(names[j])) {
11598                            mProvidersByAuthority.put(names[j], p);
11599                            if (p.info.authority == null) {
11600                                p.info.authority = names[j];
11601                            } else {
11602                                p.info.authority = p.info.authority + ";" + names[j];
11603                            }
11604                            if (DEBUG_PACKAGE_SCANNING) {
11605                                if (chatty)
11606                                    Log.d(TAG, "Registered content provider: " + names[j]
11607                                            + ", className = " + p.info.name + ", isSyncable = "
11608                                            + p.info.isSyncable);
11609                            }
11610                        } else {
11611                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11612                            Slog.w(TAG, "Skipping provider name " + names[j] +
11613                                    " (in package " + pkg.applicationInfo.packageName +
11614                                    "): name already used by "
11615                                    + ((other != null && other.getComponentName() != null)
11616                                            ? other.getComponentName().getPackageName() : "?"));
11617                        }
11618                    }
11619                }
11620                if (chatty) {
11621                    if (r == null) {
11622                        r = new StringBuilder(256);
11623                    } else {
11624                        r.append(' ');
11625                    }
11626                    r.append(p.info.name);
11627                }
11628            }
11629            if (r != null) {
11630                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11631            }
11632
11633            N = pkg.services.size();
11634            r = null;
11635            for (i=0; i<N; i++) {
11636                PackageParser.Service s = pkg.services.get(i);
11637                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11638                        s.info.processName);
11639                mServices.addService(s);
11640                if (chatty) {
11641                    if (r == null) {
11642                        r = new StringBuilder(256);
11643                    } else {
11644                        r.append(' ');
11645                    }
11646                    r.append(s.info.name);
11647                }
11648            }
11649            if (r != null) {
11650                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11651            }
11652
11653            N = pkg.receivers.size();
11654            r = null;
11655            for (i=0; i<N; i++) {
11656                PackageParser.Activity a = pkg.receivers.get(i);
11657                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11658                        a.info.processName);
11659                mReceivers.addActivity(a, "receiver");
11660                if (chatty) {
11661                    if (r == null) {
11662                        r = new StringBuilder(256);
11663                    } else {
11664                        r.append(' ');
11665                    }
11666                    r.append(a.info.name);
11667                }
11668            }
11669            if (r != null) {
11670                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11671            }
11672
11673            N = pkg.activities.size();
11674            r = null;
11675            for (i=0; i<N; i++) {
11676                PackageParser.Activity a = pkg.activities.get(i);
11677                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11678                        a.info.processName);
11679                mActivities.addActivity(a, "activity");
11680                if (chatty) {
11681                    if (r == null) {
11682                        r = new StringBuilder(256);
11683                    } else {
11684                        r.append(' ');
11685                    }
11686                    r.append(a.info.name);
11687                }
11688            }
11689            if (r != null) {
11690                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11691            }
11692
11693            N = pkg.permissionGroups.size();
11694            r = null;
11695            for (i=0; i<N; i++) {
11696                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11697                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11698                final String curPackageName = cur == null ? null : cur.info.packageName;
11699                // Dont allow ephemeral apps to define new permission groups.
11700                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11701                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11702                            + pg.info.packageName
11703                            + " ignored: instant apps cannot define new permission groups.");
11704                    continue;
11705                }
11706                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11707                if (cur == null || isPackageUpdate) {
11708                    mPermissionGroups.put(pg.info.name, pg);
11709                    if (chatty) {
11710                        if (r == null) {
11711                            r = new StringBuilder(256);
11712                        } else {
11713                            r.append(' ');
11714                        }
11715                        if (isPackageUpdate) {
11716                            r.append("UPD:");
11717                        }
11718                        r.append(pg.info.name);
11719                    }
11720                } else {
11721                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11722                            + pg.info.packageName + " ignored: original from "
11723                            + cur.info.packageName);
11724                    if (chatty) {
11725                        if (r == null) {
11726                            r = new StringBuilder(256);
11727                        } else {
11728                            r.append(' ');
11729                        }
11730                        r.append("DUP:");
11731                        r.append(pg.info.name);
11732                    }
11733                }
11734            }
11735            if (r != null) {
11736                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11737            }
11738
11739            N = pkg.permissions.size();
11740            r = null;
11741            for (i=0; i<N; i++) {
11742                PackageParser.Permission p = pkg.permissions.get(i);
11743
11744                // Dont allow ephemeral apps to define new permissions.
11745                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11746                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11747                            + p.info.packageName
11748                            + " ignored: instant apps cannot define new permissions.");
11749                    continue;
11750                }
11751
11752                // Assume by default that we did not install this permission into the system.
11753                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11754
11755                // Now that permission groups have a special meaning, we ignore permission
11756                // groups for legacy apps to prevent unexpected behavior. In particular,
11757                // permissions for one app being granted to someone just because they happen
11758                // to be in a group defined by another app (before this had no implications).
11759                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11760                    p.group = mPermissionGroups.get(p.info.group);
11761                    // Warn for a permission in an unknown group.
11762                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11763                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11764                                + p.info.packageName + " in an unknown group " + p.info.group);
11765                    }
11766                }
11767
11768                final ArrayMap<String, BasePermission> permissionMap =
11769                        p.tree ? mSettings.mPermissionTrees
11770                                : mSettings.mPermissions;
11771                final BasePermission bp = BasePermission.createOrUpdate(
11772                        permissionMap.get(p.info.name), p, pkg, mSettings.mPermissionTrees, chatty);
11773                permissionMap.put(p.info.name, bp);
11774            }
11775
11776            N = pkg.instrumentation.size();
11777            r = null;
11778            for (i=0; i<N; i++) {
11779                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11780                a.info.packageName = pkg.applicationInfo.packageName;
11781                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11782                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11783                a.info.splitNames = pkg.splitNames;
11784                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11785                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11786                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11787                a.info.dataDir = pkg.applicationInfo.dataDir;
11788                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11789                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11790                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11791                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11792                mInstrumentation.put(a.getComponentName(), a);
11793                if (chatty) {
11794                    if (r == null) {
11795                        r = new StringBuilder(256);
11796                    } else {
11797                        r.append(' ');
11798                    }
11799                    r.append(a.info.name);
11800                }
11801            }
11802            if (r != null) {
11803                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11804            }
11805
11806            if (pkg.protectedBroadcasts != null) {
11807                N = pkg.protectedBroadcasts.size();
11808                synchronized (mProtectedBroadcasts) {
11809                    for (i = 0; i < N; i++) {
11810                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11811                    }
11812                }
11813            }
11814        }
11815
11816        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11817    }
11818
11819    /**
11820     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11821     * is derived purely on the basis of the contents of {@code scanFile} and
11822     * {@code cpuAbiOverride}.
11823     *
11824     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11825     */
11826    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11827                                 String cpuAbiOverride, boolean extractLibs,
11828                                 File appLib32InstallDir)
11829            throws PackageManagerException {
11830        // Give ourselves some initial paths; we'll come back for another
11831        // pass once we've determined ABI below.
11832        setNativeLibraryPaths(pkg, appLib32InstallDir);
11833
11834        // We would never need to extract libs for forward-locked and external packages,
11835        // since the container service will do it for us. We shouldn't attempt to
11836        // extract libs from system app when it was not updated.
11837        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11838                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11839            extractLibs = false;
11840        }
11841
11842        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11843        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11844
11845        NativeLibraryHelper.Handle handle = null;
11846        try {
11847            handle = NativeLibraryHelper.Handle.create(pkg);
11848            // TODO(multiArch): This can be null for apps that didn't go through the
11849            // usual installation process. We can calculate it again, like we
11850            // do during install time.
11851            //
11852            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11853            // unnecessary.
11854            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11855
11856            // Null out the abis so that they can be recalculated.
11857            pkg.applicationInfo.primaryCpuAbi = null;
11858            pkg.applicationInfo.secondaryCpuAbi = null;
11859            if (isMultiArch(pkg.applicationInfo)) {
11860                // Warn if we've set an abiOverride for multi-lib packages..
11861                // By definition, we need to copy both 32 and 64 bit libraries for
11862                // such packages.
11863                if (pkg.cpuAbiOverride != null
11864                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11865                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11866                }
11867
11868                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11869                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11870                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11871                    if (extractLibs) {
11872                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11873                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11874                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11875                                useIsaSpecificSubdirs);
11876                    } else {
11877                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11878                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11879                    }
11880                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11881                }
11882
11883                // Shared library native code should be in the APK zip aligned
11884                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11885                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11886                            "Shared library native lib extraction not supported");
11887                }
11888
11889                maybeThrowExceptionForMultiArchCopy(
11890                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11891
11892                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11893                    if (extractLibs) {
11894                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11895                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11896                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11897                                useIsaSpecificSubdirs);
11898                    } else {
11899                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11900                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11901                    }
11902                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11903                }
11904
11905                maybeThrowExceptionForMultiArchCopy(
11906                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11907
11908                if (abi64 >= 0) {
11909                    // Shared library native libs should be in the APK zip aligned
11910                    if (extractLibs && pkg.isLibrary()) {
11911                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11912                                "Shared library native lib extraction not supported");
11913                    }
11914                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11915                }
11916
11917                if (abi32 >= 0) {
11918                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11919                    if (abi64 >= 0) {
11920                        if (pkg.use32bitAbi) {
11921                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11922                            pkg.applicationInfo.primaryCpuAbi = abi;
11923                        } else {
11924                            pkg.applicationInfo.secondaryCpuAbi = abi;
11925                        }
11926                    } else {
11927                        pkg.applicationInfo.primaryCpuAbi = abi;
11928                    }
11929                }
11930            } else {
11931                String[] abiList = (cpuAbiOverride != null) ?
11932                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11933
11934                // Enable gross and lame hacks for apps that are built with old
11935                // SDK tools. We must scan their APKs for renderscript bitcode and
11936                // not launch them if it's present. Don't bother checking on devices
11937                // that don't have 64 bit support.
11938                boolean needsRenderScriptOverride = false;
11939                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11940                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11941                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11942                    needsRenderScriptOverride = true;
11943                }
11944
11945                final int copyRet;
11946                if (extractLibs) {
11947                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11948                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11949                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11950                } else {
11951                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11952                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11953                }
11954                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11955
11956                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11957                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11958                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11959                }
11960
11961                if (copyRet >= 0) {
11962                    // Shared libraries that have native libs must be multi-architecture
11963                    if (pkg.isLibrary()) {
11964                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11965                                "Shared library with native libs must be multiarch");
11966                    }
11967                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11968                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11969                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11970                } else if (needsRenderScriptOverride) {
11971                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11972                }
11973            }
11974        } catch (IOException ioe) {
11975            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11976        } finally {
11977            IoUtils.closeQuietly(handle);
11978        }
11979
11980        // Now that we've calculated the ABIs and determined if it's an internal app,
11981        // we will go ahead and populate the nativeLibraryPath.
11982        setNativeLibraryPaths(pkg, appLib32InstallDir);
11983    }
11984
11985    /**
11986     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11987     * i.e, so that all packages can be run inside a single process if required.
11988     *
11989     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11990     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11991     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11992     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11993     * updating a package that belongs to a shared user.
11994     *
11995     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11996     * adds unnecessary complexity.
11997     */
11998    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11999            PackageParser.Package scannedPackage) {
12000        String requiredInstructionSet = null;
12001        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12002            requiredInstructionSet = VMRuntime.getInstructionSet(
12003                     scannedPackage.applicationInfo.primaryCpuAbi);
12004        }
12005
12006        PackageSetting requirer = null;
12007        for (PackageSetting ps : packagesForUser) {
12008            // If packagesForUser contains scannedPackage, we skip it. This will happen
12009            // when scannedPackage is an update of an existing package. Without this check,
12010            // we will never be able to change the ABI of any package belonging to a shared
12011            // user, even if it's compatible with other packages.
12012            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12013                if (ps.primaryCpuAbiString == null) {
12014                    continue;
12015                }
12016
12017                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12018                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12019                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12020                    // this but there's not much we can do.
12021                    String errorMessage = "Instruction set mismatch, "
12022                            + ((requirer == null) ? "[caller]" : requirer)
12023                            + " requires " + requiredInstructionSet + " whereas " + ps
12024                            + " requires " + instructionSet;
12025                    Slog.w(TAG, errorMessage);
12026                }
12027
12028                if (requiredInstructionSet == null) {
12029                    requiredInstructionSet = instructionSet;
12030                    requirer = ps;
12031                }
12032            }
12033        }
12034
12035        if (requiredInstructionSet != null) {
12036            String adjustedAbi;
12037            if (requirer != null) {
12038                // requirer != null implies that either scannedPackage was null or that scannedPackage
12039                // did not require an ABI, in which case we have to adjust scannedPackage to match
12040                // the ABI of the set (which is the same as requirer's ABI)
12041                adjustedAbi = requirer.primaryCpuAbiString;
12042                if (scannedPackage != null) {
12043                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12044                }
12045            } else {
12046                // requirer == null implies that we're updating all ABIs in the set to
12047                // match scannedPackage.
12048                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12049            }
12050
12051            for (PackageSetting ps : packagesForUser) {
12052                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12053                    if (ps.primaryCpuAbiString != null) {
12054                        continue;
12055                    }
12056
12057                    ps.primaryCpuAbiString = adjustedAbi;
12058                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12059                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12060                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12061                        if (DEBUG_ABI_SELECTION) {
12062                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12063                                    + " (requirer="
12064                                    + (requirer != null ? requirer.pkg : "null")
12065                                    + ", scannedPackage="
12066                                    + (scannedPackage != null ? scannedPackage : "null")
12067                                    + ")");
12068                        }
12069                        try {
12070                            mInstaller.rmdex(ps.codePathString,
12071                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12072                        } catch (InstallerException ignored) {
12073                        }
12074                    }
12075                }
12076            }
12077        }
12078    }
12079
12080    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12081        synchronized (mPackages) {
12082            mResolverReplaced = true;
12083            // Set up information for custom user intent resolution activity.
12084            mResolveActivity.applicationInfo = pkg.applicationInfo;
12085            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12086            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12087            mResolveActivity.processName = pkg.applicationInfo.packageName;
12088            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12089            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12090                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12091            mResolveActivity.theme = 0;
12092            mResolveActivity.exported = true;
12093            mResolveActivity.enabled = true;
12094            mResolveInfo.activityInfo = mResolveActivity;
12095            mResolveInfo.priority = 0;
12096            mResolveInfo.preferredOrder = 0;
12097            mResolveInfo.match = 0;
12098            mResolveComponentName = mCustomResolverComponentName;
12099            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12100                    mResolveComponentName);
12101        }
12102    }
12103
12104    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12105        if (installerActivity == null) {
12106            if (DEBUG_EPHEMERAL) {
12107                Slog.d(TAG, "Clear ephemeral installer activity");
12108            }
12109            mInstantAppInstallerActivity = null;
12110            return;
12111        }
12112
12113        if (DEBUG_EPHEMERAL) {
12114            Slog.d(TAG, "Set ephemeral installer activity: "
12115                    + installerActivity.getComponentName());
12116        }
12117        // Set up information for ephemeral installer activity
12118        mInstantAppInstallerActivity = installerActivity;
12119        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12120                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12121        mInstantAppInstallerActivity.exported = true;
12122        mInstantAppInstallerActivity.enabled = true;
12123        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12124        mInstantAppInstallerInfo.priority = 0;
12125        mInstantAppInstallerInfo.preferredOrder = 1;
12126        mInstantAppInstallerInfo.isDefault = true;
12127        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12128                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12129    }
12130
12131    private static String calculateBundledApkRoot(final String codePathString) {
12132        final File codePath = new File(codePathString);
12133        final File codeRoot;
12134        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12135            codeRoot = Environment.getRootDirectory();
12136        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12137            codeRoot = Environment.getOemDirectory();
12138        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12139            codeRoot = Environment.getVendorDirectory();
12140        } else {
12141            // Unrecognized code path; take its top real segment as the apk root:
12142            // e.g. /something/app/blah.apk => /something
12143            try {
12144                File f = codePath.getCanonicalFile();
12145                File parent = f.getParentFile();    // non-null because codePath is a file
12146                File tmp;
12147                while ((tmp = parent.getParentFile()) != null) {
12148                    f = parent;
12149                    parent = tmp;
12150                }
12151                codeRoot = f;
12152                Slog.w(TAG, "Unrecognized code path "
12153                        + codePath + " - using " + codeRoot);
12154            } catch (IOException e) {
12155                // Can't canonicalize the code path -- shenanigans?
12156                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12157                return Environment.getRootDirectory().getPath();
12158            }
12159        }
12160        return codeRoot.getPath();
12161    }
12162
12163    /**
12164     * Derive and set the location of native libraries for the given package,
12165     * which varies depending on where and how the package was installed.
12166     */
12167    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12168        final ApplicationInfo info = pkg.applicationInfo;
12169        final String codePath = pkg.codePath;
12170        final File codeFile = new File(codePath);
12171        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12172        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12173
12174        info.nativeLibraryRootDir = null;
12175        info.nativeLibraryRootRequiresIsa = false;
12176        info.nativeLibraryDir = null;
12177        info.secondaryNativeLibraryDir = null;
12178
12179        if (isApkFile(codeFile)) {
12180            // Monolithic install
12181            if (bundledApp) {
12182                // If "/system/lib64/apkname" exists, assume that is the per-package
12183                // native library directory to use; otherwise use "/system/lib/apkname".
12184                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12185                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12186                        getPrimaryInstructionSet(info));
12187
12188                // This is a bundled system app so choose the path based on the ABI.
12189                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12190                // is just the default path.
12191                final String apkName = deriveCodePathName(codePath);
12192                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12193                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12194                        apkName).getAbsolutePath();
12195
12196                if (info.secondaryCpuAbi != null) {
12197                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12198                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12199                            secondaryLibDir, apkName).getAbsolutePath();
12200                }
12201            } else if (asecApp) {
12202                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12203                        .getAbsolutePath();
12204            } else {
12205                final String apkName = deriveCodePathName(codePath);
12206                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12207                        .getAbsolutePath();
12208            }
12209
12210            info.nativeLibraryRootRequiresIsa = false;
12211            info.nativeLibraryDir = info.nativeLibraryRootDir;
12212        } else {
12213            // Cluster install
12214            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12215            info.nativeLibraryRootRequiresIsa = true;
12216
12217            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12218                    getPrimaryInstructionSet(info)).getAbsolutePath();
12219
12220            if (info.secondaryCpuAbi != null) {
12221                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12222                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12223            }
12224        }
12225    }
12226
12227    /**
12228     * Calculate the abis and roots for a bundled app. These can uniquely
12229     * be determined from the contents of the system partition, i.e whether
12230     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12231     * of this information, and instead assume that the system was built
12232     * sensibly.
12233     */
12234    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12235                                           PackageSetting pkgSetting) {
12236        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12237
12238        // If "/system/lib64/apkname" exists, assume that is the per-package
12239        // native library directory to use; otherwise use "/system/lib/apkname".
12240        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12241        setBundledAppAbi(pkg, apkRoot, apkName);
12242        // pkgSetting might be null during rescan following uninstall of updates
12243        // to a bundled app, so accommodate that possibility.  The settings in
12244        // that case will be established later from the parsed package.
12245        //
12246        // If the settings aren't null, sync them up with what we've just derived.
12247        // note that apkRoot isn't stored in the package settings.
12248        if (pkgSetting != null) {
12249            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12250            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12251        }
12252    }
12253
12254    /**
12255     * Deduces the ABI of a bundled app and sets the relevant fields on the
12256     * parsed pkg object.
12257     *
12258     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12259     *        under which system libraries are installed.
12260     * @param apkName the name of the installed package.
12261     */
12262    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12263        final File codeFile = new File(pkg.codePath);
12264
12265        final boolean has64BitLibs;
12266        final boolean has32BitLibs;
12267        if (isApkFile(codeFile)) {
12268            // Monolithic install
12269            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12270            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12271        } else {
12272            // Cluster install
12273            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12274            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12275                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12276                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12277                has64BitLibs = (new File(rootDir, isa)).exists();
12278            } else {
12279                has64BitLibs = false;
12280            }
12281            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12282                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12283                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12284                has32BitLibs = (new File(rootDir, isa)).exists();
12285            } else {
12286                has32BitLibs = false;
12287            }
12288        }
12289
12290        if (has64BitLibs && !has32BitLibs) {
12291            // The package has 64 bit libs, but not 32 bit libs. Its primary
12292            // ABI should be 64 bit. We can safely assume here that the bundled
12293            // native libraries correspond to the most preferred ABI in the list.
12294
12295            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12296            pkg.applicationInfo.secondaryCpuAbi = null;
12297        } else if (has32BitLibs && !has64BitLibs) {
12298            // The package has 32 bit libs but not 64 bit libs. Its primary
12299            // ABI should be 32 bit.
12300
12301            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12302            pkg.applicationInfo.secondaryCpuAbi = null;
12303        } else if (has32BitLibs && has64BitLibs) {
12304            // The application has both 64 and 32 bit bundled libraries. We check
12305            // here that the app declares multiArch support, and warn if it doesn't.
12306            //
12307            // We will be lenient here and record both ABIs. The primary will be the
12308            // ABI that's higher on the list, i.e, a device that's configured to prefer
12309            // 64 bit apps will see a 64 bit primary ABI,
12310
12311            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12312                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12313            }
12314
12315            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12316                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12317                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12318            } else {
12319                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12320                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12321            }
12322        } else {
12323            pkg.applicationInfo.primaryCpuAbi = null;
12324            pkg.applicationInfo.secondaryCpuAbi = null;
12325        }
12326    }
12327
12328    private void killApplication(String pkgName, int appId, String reason) {
12329        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12330    }
12331
12332    private void killApplication(String pkgName, int appId, int userId, String reason) {
12333        // Request the ActivityManager to kill the process(only for existing packages)
12334        // so that we do not end up in a confused state while the user is still using the older
12335        // version of the application while the new one gets installed.
12336        final long token = Binder.clearCallingIdentity();
12337        try {
12338            IActivityManager am = ActivityManager.getService();
12339            if (am != null) {
12340                try {
12341                    am.killApplication(pkgName, appId, userId, reason);
12342                } catch (RemoteException e) {
12343                }
12344            }
12345        } finally {
12346            Binder.restoreCallingIdentity(token);
12347        }
12348    }
12349
12350    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12351        // Remove the parent package setting
12352        PackageSetting ps = (PackageSetting) pkg.mExtras;
12353        if (ps != null) {
12354            removePackageLI(ps, chatty);
12355        }
12356        // Remove the child package setting
12357        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12358        for (int i = 0; i < childCount; i++) {
12359            PackageParser.Package childPkg = pkg.childPackages.get(i);
12360            ps = (PackageSetting) childPkg.mExtras;
12361            if (ps != null) {
12362                removePackageLI(ps, chatty);
12363            }
12364        }
12365    }
12366
12367    void removePackageLI(PackageSetting ps, boolean chatty) {
12368        if (DEBUG_INSTALL) {
12369            if (chatty)
12370                Log.d(TAG, "Removing package " + ps.name);
12371        }
12372
12373        // writer
12374        synchronized (mPackages) {
12375            mPackages.remove(ps.name);
12376            final PackageParser.Package pkg = ps.pkg;
12377            if (pkg != null) {
12378                cleanPackageDataStructuresLILPw(pkg, chatty);
12379            }
12380        }
12381    }
12382
12383    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12384        if (DEBUG_INSTALL) {
12385            if (chatty)
12386                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12387        }
12388
12389        // writer
12390        synchronized (mPackages) {
12391            // Remove the parent package
12392            mPackages.remove(pkg.applicationInfo.packageName);
12393            cleanPackageDataStructuresLILPw(pkg, chatty);
12394
12395            // Remove the child packages
12396            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12397            for (int i = 0; i < childCount; i++) {
12398                PackageParser.Package childPkg = pkg.childPackages.get(i);
12399                mPackages.remove(childPkg.applicationInfo.packageName);
12400                cleanPackageDataStructuresLILPw(childPkg, chatty);
12401            }
12402        }
12403    }
12404
12405    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12406        int N = pkg.providers.size();
12407        StringBuilder r = null;
12408        int i;
12409        for (i=0; i<N; i++) {
12410            PackageParser.Provider p = pkg.providers.get(i);
12411            mProviders.removeProvider(p);
12412            if (p.info.authority == null) {
12413
12414                /* There was another ContentProvider with this authority when
12415                 * this app was installed so this authority is null,
12416                 * Ignore it as we don't have to unregister the provider.
12417                 */
12418                continue;
12419            }
12420            String names[] = p.info.authority.split(";");
12421            for (int j = 0; j < names.length; j++) {
12422                if (mProvidersByAuthority.get(names[j]) == p) {
12423                    mProvidersByAuthority.remove(names[j]);
12424                    if (DEBUG_REMOVE) {
12425                        if (chatty)
12426                            Log.d(TAG, "Unregistered content provider: " + names[j]
12427                                    + ", className = " + p.info.name + ", isSyncable = "
12428                                    + p.info.isSyncable);
12429                    }
12430                }
12431            }
12432            if (DEBUG_REMOVE && chatty) {
12433                if (r == null) {
12434                    r = new StringBuilder(256);
12435                } else {
12436                    r.append(' ');
12437                }
12438                r.append(p.info.name);
12439            }
12440        }
12441        if (r != null) {
12442            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12443        }
12444
12445        N = pkg.services.size();
12446        r = null;
12447        for (i=0; i<N; i++) {
12448            PackageParser.Service s = pkg.services.get(i);
12449            mServices.removeService(s);
12450            if (chatty) {
12451                if (r == null) {
12452                    r = new StringBuilder(256);
12453                } else {
12454                    r.append(' ');
12455                }
12456                r.append(s.info.name);
12457            }
12458        }
12459        if (r != null) {
12460            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12461        }
12462
12463        N = pkg.receivers.size();
12464        r = null;
12465        for (i=0; i<N; i++) {
12466            PackageParser.Activity a = pkg.receivers.get(i);
12467            mReceivers.removeActivity(a, "receiver");
12468            if (DEBUG_REMOVE && chatty) {
12469                if (r == null) {
12470                    r = new StringBuilder(256);
12471                } else {
12472                    r.append(' ');
12473                }
12474                r.append(a.info.name);
12475            }
12476        }
12477        if (r != null) {
12478            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12479        }
12480
12481        N = pkg.activities.size();
12482        r = null;
12483        for (i=0; i<N; i++) {
12484            PackageParser.Activity a = pkg.activities.get(i);
12485            mActivities.removeActivity(a, "activity");
12486            if (DEBUG_REMOVE && chatty) {
12487                if (r == null) {
12488                    r = new StringBuilder(256);
12489                } else {
12490                    r.append(' ');
12491                }
12492                r.append(a.info.name);
12493            }
12494        }
12495        if (r != null) {
12496            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12497        }
12498
12499        N = pkg.permissions.size();
12500        r = null;
12501        for (i=0; i<N; i++) {
12502            PackageParser.Permission p = pkg.permissions.get(i);
12503            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12504            if (bp == null) {
12505                bp = mSettings.mPermissionTrees.get(p.info.name);
12506            }
12507            if (bp != null && bp.isPermission(p)) {
12508                bp.setPermission(null);
12509                if (DEBUG_REMOVE && chatty) {
12510                    if (r == null) {
12511                        r = new StringBuilder(256);
12512                    } else {
12513                        r.append(' ');
12514                    }
12515                    r.append(p.info.name);
12516                }
12517            }
12518            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12519                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12520                if (appOpPkgs != null) {
12521                    appOpPkgs.remove(pkg.packageName);
12522                }
12523            }
12524        }
12525        if (r != null) {
12526            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12527        }
12528
12529        N = pkg.requestedPermissions.size();
12530        r = null;
12531        for (i=0; i<N; i++) {
12532            String perm = pkg.requestedPermissions.get(i);
12533            BasePermission bp = mSettings.mPermissions.get(perm);
12534            if (bp != null && bp.isAppOp()) {
12535                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12536                if (appOpPkgs != null) {
12537                    appOpPkgs.remove(pkg.packageName);
12538                    if (appOpPkgs.isEmpty()) {
12539                        mAppOpPermissionPackages.remove(perm);
12540                    }
12541                }
12542            }
12543        }
12544        if (r != null) {
12545            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12546        }
12547
12548        N = pkg.instrumentation.size();
12549        r = null;
12550        for (i=0; i<N; i++) {
12551            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12552            mInstrumentation.remove(a.getComponentName());
12553            if (DEBUG_REMOVE && chatty) {
12554                if (r == null) {
12555                    r = new StringBuilder(256);
12556                } else {
12557                    r.append(' ');
12558                }
12559                r.append(a.info.name);
12560            }
12561        }
12562        if (r != null) {
12563            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12564        }
12565
12566        r = null;
12567        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12568            // Only system apps can hold shared libraries.
12569            if (pkg.libraryNames != null) {
12570                for (i = 0; i < pkg.libraryNames.size(); i++) {
12571                    String name = pkg.libraryNames.get(i);
12572                    if (removeSharedLibraryLPw(name, 0)) {
12573                        if (DEBUG_REMOVE && chatty) {
12574                            if (r == null) {
12575                                r = new StringBuilder(256);
12576                            } else {
12577                                r.append(' ');
12578                            }
12579                            r.append(name);
12580                        }
12581                    }
12582                }
12583            }
12584        }
12585
12586        r = null;
12587
12588        // Any package can hold static shared libraries.
12589        if (pkg.staticSharedLibName != null) {
12590            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12591                if (DEBUG_REMOVE && chatty) {
12592                    if (r == null) {
12593                        r = new StringBuilder(256);
12594                    } else {
12595                        r.append(' ');
12596                    }
12597                    r.append(pkg.staticSharedLibName);
12598                }
12599            }
12600        }
12601
12602        if (r != null) {
12603            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12604        }
12605    }
12606
12607    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12608        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12609            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12610                return true;
12611            }
12612        }
12613        return false;
12614    }
12615
12616    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12617    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12618    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12619
12620    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12621        // Update the parent permissions
12622        updatePermissionsLPw(pkg.packageName, pkg, flags);
12623        // Update the child permissions
12624        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12625        for (int i = 0; i < childCount; i++) {
12626            PackageParser.Package childPkg = pkg.childPackages.get(i);
12627            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12628        }
12629    }
12630
12631    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12632            int flags) {
12633        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12634        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12635    }
12636
12637    private void updatePermissionsLPw(String changingPkg,
12638            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12639        // TODO: Most of the methods exposing BasePermission internals [source package name,
12640        // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
12641        // have package settings, we should make note of it elsewhere [map between
12642        // source package name and BasePermission] and cycle through that here. Then we
12643        // define a single method on BasePermission that takes a PackageSetting, changing
12644        // package name and a package.
12645        // NOTE: With this approach, we also don't need to tree trees differently than
12646        // normal permissions. Today, we need two separate loops because these BasePermission
12647        // objects are stored separately.
12648        // Make sure there are no dangling permission trees.
12649        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12650        while (it.hasNext()) {
12651            final BasePermission bp = it.next();
12652            if (bp.getSourcePackageSetting() == null) {
12653                // We may not yet have parsed the package, so just see if
12654                // we still know about its settings.
12655                bp.setSourcePackageSetting(mSettings.mPackages.get(bp.getSourcePackageName()));
12656            }
12657            if (bp.getSourcePackageSetting() == null) {
12658                Slog.w(TAG, "Removing dangling permission tree: " + bp.getName()
12659                        + " from package " + bp.getSourcePackageName());
12660                it.remove();
12661            } else if (changingPkg != null && changingPkg.equals(bp.getSourcePackageName())) {
12662                if (pkgInfo == null || !hasPermission(pkgInfo, bp.getName())) {
12663                    Slog.i(TAG, "Removing old permission tree: " + bp.getName()
12664                            + " from package " + bp.getSourcePackageName());
12665                    flags |= UPDATE_PERMISSIONS_ALL;
12666                    it.remove();
12667                }
12668            }
12669        }
12670
12671        // Make sure all dynamic permissions have been assigned to a package,
12672        // and make sure there are no dangling permissions.
12673        it = mSettings.mPermissions.values().iterator();
12674        while (it.hasNext()) {
12675            final BasePermission bp = it.next();
12676            if (bp.isDynamic()) {
12677                bp.updateDynamicPermission(mSettings.mPermissionTrees);
12678            }
12679            if (bp.getSourcePackageSetting() == null) {
12680                // We may not yet have parsed the package, so just see if
12681                // we still know about its settings.
12682                bp.setSourcePackageSetting(mSettings.mPackages.get(bp.getSourcePackageName()));
12683            }
12684            if (bp.getSourcePackageSetting() == null) {
12685                Slog.w(TAG, "Removing dangling permission: " + bp.getName()
12686                        + " from package " + bp.getSourcePackageName());
12687                it.remove();
12688            } else if (changingPkg != null && changingPkg.equals(bp.getSourcePackageName())) {
12689                if (pkgInfo == null || !hasPermission(pkgInfo, bp.getName())) {
12690                    Slog.i(TAG, "Removing old permission: " + bp.getName()
12691                            + " from package " + bp.getSourcePackageName());
12692                    flags |= UPDATE_PERMISSIONS_ALL;
12693                    it.remove();
12694                }
12695            }
12696        }
12697
12698        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12699        // Now update the permissions for all packages, in particular
12700        // replace the granted permissions of the system packages.
12701        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12702            for (PackageParser.Package pkg : mPackages.values()) {
12703                if (pkg != pkgInfo) {
12704                    // Only replace for packages on requested volume
12705                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12706                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12707                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12708                    grantPermissionsLPw(pkg, replace, changingPkg);
12709                }
12710            }
12711        }
12712
12713        if (pkgInfo != null) {
12714            // Only replace for packages on requested volume
12715            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12716            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12717                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12718            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12719        }
12720        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12721    }
12722
12723    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12724            String packageOfInterest) {
12725        // IMPORTANT: There are two types of permissions: install and runtime.
12726        // Install time permissions are granted when the app is installed to
12727        // all device users and users added in the future. Runtime permissions
12728        // are granted at runtime explicitly to specific users. Normal and signature
12729        // protected permissions are install time permissions. Dangerous permissions
12730        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12731        // otherwise they are runtime permissions. This function does not manage
12732        // runtime permissions except for the case an app targeting Lollipop MR1
12733        // being upgraded to target a newer SDK, in which case dangerous permissions
12734        // are transformed from install time to runtime ones.
12735
12736        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12737        if (ps == null) {
12738            return;
12739        }
12740
12741        PermissionsState permissionsState = ps.getPermissionsState();
12742        PermissionsState origPermissions = permissionsState;
12743
12744        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12745
12746        boolean runtimePermissionsRevoked = false;
12747        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12748
12749        boolean changedInstallPermission = false;
12750
12751        if (replace) {
12752            ps.installPermissionsFixed = false;
12753            if (!ps.isSharedUser()) {
12754                origPermissions = new PermissionsState(permissionsState);
12755                permissionsState.reset();
12756            } else {
12757                // We need to know only about runtime permission changes since the
12758                // calling code always writes the install permissions state but
12759                // the runtime ones are written only if changed. The only cases of
12760                // changed runtime permissions here are promotion of an install to
12761                // runtime and revocation of a runtime from a shared user.
12762                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12763                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12764                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12765                    runtimePermissionsRevoked = true;
12766                }
12767            }
12768        }
12769
12770        permissionsState.setGlobalGids(mGlobalGids);
12771
12772        final int N = pkg.requestedPermissions.size();
12773        for (int i=0; i<N; i++) {
12774            final String name = pkg.requestedPermissions.get(i);
12775            final BasePermission bp = mSettings.mPermissions.get(name);
12776            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12777                    >= Build.VERSION_CODES.M;
12778
12779            if (DEBUG_INSTALL) {
12780                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12781            }
12782
12783            if (bp == null || bp.getSourcePackageSetting() == null) {
12784                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12785                    if (DEBUG_PERMISSIONS) {
12786                        Slog.i(TAG, "Unknown permission " + name
12787                                + " in package " + pkg.packageName);
12788                    }
12789                }
12790                continue;
12791            }
12792
12793
12794            // Limit ephemeral apps to ephemeral allowed permissions.
12795            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12796                if (DEBUG_PERMISSIONS) {
12797                    Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() + " for package "
12798                            + pkg.packageName);
12799                }
12800                continue;
12801            }
12802
12803            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12804                if (DEBUG_PERMISSIONS) {
12805                    Log.i(TAG, "Denying runtime-only permission " + bp.getName() + " for package "
12806                            + pkg.packageName);
12807                }
12808                continue;
12809            }
12810
12811            final String perm = bp.getName();
12812            boolean allowedSig = false;
12813            int grant = GRANT_DENIED;
12814
12815            // Keep track of app op permissions.
12816            if (bp.isAppOp()) {
12817                ArraySet<String> pkgs = mAppOpPermissionPackages.get(perm);
12818                if (pkgs == null) {
12819                    pkgs = new ArraySet<>();
12820                    mAppOpPermissionPackages.put(perm, pkgs);
12821                }
12822                pkgs.add(pkg.packageName);
12823            }
12824
12825            if (bp.isNormal()) {
12826                // For all apps normal permissions are install time ones.
12827                grant = GRANT_INSTALL;
12828            } else if (bp.isRuntime()) {
12829                // If a permission review is required for legacy apps we represent
12830                // their permissions as always granted runtime ones since we need
12831                // to keep the review required permission flag per user while an
12832                // install permission's state is shared across all users.
12833                if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12834                    // For legacy apps dangerous permissions are install time ones.
12835                    grant = GRANT_INSTALL;
12836                } else if (origPermissions.hasInstallPermission(bp.getName())) {
12837                    // For legacy apps that became modern, install becomes runtime.
12838                    grant = GRANT_UPGRADE;
12839                } else if (mPromoteSystemApps
12840                        && isSystemApp(ps)
12841                        && mExistingSystemPackages.contains(ps.name)) {
12842                    // For legacy system apps, install becomes runtime.
12843                    // We cannot check hasInstallPermission() for system apps since those
12844                    // permissions were granted implicitly and not persisted pre-M.
12845                    grant = GRANT_UPGRADE;
12846                } else {
12847                    // For modern apps keep runtime permissions unchanged.
12848                    grant = GRANT_RUNTIME;
12849                }
12850            } else if (bp.isSignature()) {
12851                // For all apps signature permissions are install time ones.
12852                allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12853                if (allowedSig) {
12854                    grant = GRANT_INSTALL;
12855                }
12856            }
12857
12858            if (DEBUG_PERMISSIONS) {
12859                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12860            }
12861
12862            if (grant != GRANT_DENIED) {
12863                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12864                    // If this is an existing, non-system package, then
12865                    // we can't add any new permissions to it.
12866                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12867                        // Except...  if this is a permission that was added
12868                        // to the platform (note: need to only do this when
12869                        // updating the platform).
12870                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12871                            grant = GRANT_DENIED;
12872                        }
12873                    }
12874                }
12875
12876                switch (grant) {
12877                    case GRANT_INSTALL: {
12878                        // Revoke this as runtime permission to handle the case of
12879                        // a runtime permission being downgraded to an install one.
12880                        // Also in permission review mode we keep dangerous permissions
12881                        // for legacy apps
12882                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12883                            if (origPermissions.getRuntimePermissionState(
12884                                    perm, userId) != null) {
12885                                // Revoke the runtime permission and clear the flags.
12886                                origPermissions.revokeRuntimePermission(bp, userId);
12887                                origPermissions.updatePermissionFlags(bp, userId,
12888                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12889                                // If we revoked a permission permission, we have to write.
12890                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12891                                        changedRuntimePermissionUserIds, userId);
12892                            }
12893                        }
12894                        // Grant an install permission.
12895                        if (permissionsState.grantInstallPermission(bp) !=
12896                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12897                            changedInstallPermission = true;
12898                        }
12899                    } break;
12900
12901                    case GRANT_RUNTIME: {
12902                        // Grant previously granted runtime permissions.
12903                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12904                            PermissionState permissionState = origPermissions
12905                                    .getRuntimePermissionState(perm, userId);
12906                            int flags = permissionState != null
12907                                    ? permissionState.getFlags() : 0;
12908                            if (origPermissions.hasRuntimePermission(perm, userId)) {
12909                                // Don't propagate the permission in a permission review mode if
12910                                // the former was revoked, i.e. marked to not propagate on upgrade.
12911                                // Note that in a permission review mode install permissions are
12912                                // represented as constantly granted runtime ones since we need to
12913                                // keep a per user state associated with the permission. Also the
12914                                // revoke on upgrade flag is no longer applicable and is reset.
12915                                final boolean revokeOnUpgrade = (flags & PackageManager
12916                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12917                                if (revokeOnUpgrade) {
12918                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12919                                    // Since we changed the flags, we have to write.
12920                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12921                                            changedRuntimePermissionUserIds, userId);
12922                                }
12923                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12924                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12925                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12926                                        // If we cannot put the permission as it was,
12927                                        // we have to write.
12928                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12929                                                changedRuntimePermissionUserIds, userId);
12930                                    }
12931                                }
12932
12933                                // If the app supports runtime permissions no need for a review.
12934                                if (mPermissionReviewRequired
12935                                        && appSupportsRuntimePermissions
12936                                        && (flags & PackageManager
12937                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12938                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12939                                    // Since we changed the flags, we have to write.
12940                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12941                                            changedRuntimePermissionUserIds, userId);
12942                                }
12943                            } else if (mPermissionReviewRequired
12944                                    && !appSupportsRuntimePermissions) {
12945                                // For legacy apps that need a permission review, every new
12946                                // runtime permission is granted but it is pending a review.
12947                                // We also need to review only platform defined runtime
12948                                // permissions as these are the only ones the platform knows
12949                                // how to disable the API to simulate revocation as legacy
12950                                // apps don't expect to run with revoked permissions.
12951                                if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
12952                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12953                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12954                                        // We changed the flags, hence have to write.
12955                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12956                                                changedRuntimePermissionUserIds, userId);
12957                                    }
12958                                }
12959                                if (permissionsState.grantRuntimePermission(bp, userId)
12960                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12961                                    // We changed the permission, hence have to write.
12962                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12963                                            changedRuntimePermissionUserIds, userId);
12964                                }
12965                            }
12966                            // Propagate the permission flags.
12967                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12968                        }
12969                    } break;
12970
12971                    case GRANT_UPGRADE: {
12972                        // Grant runtime permissions for a previously held install permission.
12973                        PermissionState permissionState = origPermissions
12974                                .getInstallPermissionState(perm);
12975                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12976
12977                        if (origPermissions.revokeInstallPermission(bp)
12978                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12979                            // We will be transferring the permission flags, so clear them.
12980                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12981                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12982                            changedInstallPermission = true;
12983                        }
12984
12985                        // If the permission is not to be promoted to runtime we ignore it and
12986                        // also its other flags as they are not applicable to install permissions.
12987                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12988                            for (int userId : currentUserIds) {
12989                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12990                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12991                                    // Transfer the permission flags.
12992                                    permissionsState.updatePermissionFlags(bp, userId,
12993                                            flags, flags);
12994                                    // If we granted the permission, we have to write.
12995                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12996                                            changedRuntimePermissionUserIds, userId);
12997                                }
12998                            }
12999                        }
13000                    } break;
13001
13002                    default: {
13003                        if (packageOfInterest == null
13004                                || packageOfInterest.equals(pkg.packageName)) {
13005                            if (DEBUG_PERMISSIONS) {
13006                                Slog.i(TAG, "Not granting permission " + perm
13007                                        + " to package " + pkg.packageName
13008                                        + " because it was previously installed without");
13009                            }
13010                        }
13011                    } break;
13012                }
13013            } else {
13014                if (permissionsState.revokeInstallPermission(bp) !=
13015                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13016                    // Also drop the permission flags.
13017                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13018                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13019                    changedInstallPermission = true;
13020                    Slog.i(TAG, "Un-granting permission " + perm
13021                            + " from package " + pkg.packageName
13022                            + " (protectionLevel=" + bp.getProtectionLevel()
13023                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13024                            + ")");
13025                } else if (bp.isAppOp()) {
13026                    // Don't print warning for app op permissions, since it is fine for them
13027                    // not to be granted, there is a UI for the user to decide.
13028                    if (DEBUG_PERMISSIONS
13029                            && (packageOfInterest == null
13030                                    || packageOfInterest.equals(pkg.packageName))) {
13031                        Slog.i(TAG, "Not granting permission " + perm
13032                                + " to package " + pkg.packageName
13033                                + " (protectionLevel=" + bp.getProtectionLevel()
13034                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13035                                + ")");
13036                    }
13037                }
13038            }
13039        }
13040
13041        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13042                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13043            // This is the first that we have heard about this package, so the
13044            // permissions we have now selected are fixed until explicitly
13045            // changed.
13046            ps.installPermissionsFixed = true;
13047        }
13048
13049        // Persist the runtime permissions state for users with changes. If permissions
13050        // were revoked because no app in the shared user declares them we have to
13051        // write synchronously to avoid losing runtime permissions state.
13052        for (int userId : changedRuntimePermissionUserIds) {
13053            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13054        }
13055    }
13056
13057    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13058        boolean allowed = false;
13059        final int NP = PackageParser.NEW_PERMISSIONS.length;
13060        for (int ip=0; ip<NP; ip++) {
13061            final PackageParser.NewPermissionInfo npi
13062                    = PackageParser.NEW_PERMISSIONS[ip];
13063            if (npi.name.equals(perm)
13064                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13065                allowed = true;
13066                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13067                        + pkg.packageName);
13068                break;
13069            }
13070        }
13071        return allowed;
13072    }
13073
13074    /**
13075     * Determines whether a package is whitelisted for a particular privapp permission.
13076     *
13077     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
13078     *
13079     * <p>This handles parent/child apps.
13080     */
13081    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
13082        ArraySet<String> wlPermissions = SystemConfig.getInstance()
13083                .getPrivAppPermissions(pkg.packageName);
13084        // Let's check if this package is whitelisted...
13085        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13086        // If it's not, we'll also tail-recurse to the parent.
13087        return whitelisted ||
13088                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
13089    }
13090
13091    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13092            BasePermission bp, PermissionsState origPermissions) {
13093        boolean oemPermission = bp.isOEM();
13094        boolean privilegedPermission = bp.isPrivileged();
13095        boolean privappPermissionsDisable =
13096                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13097        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
13098        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13099        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13100                && !platformPackage && platformPermission) {
13101            if (!hasPrivappWhitelistEntry(perm, pkg)) {
13102                Slog.w(TAG, "Privileged permission " + perm + " for package "
13103                        + pkg.packageName + " - not in privapp-permissions whitelist");
13104                // Only report violations for apps on system image
13105                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13106                    // it's only a reportable violation if the permission isn't explicitly denied
13107                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13108                            .getPrivAppDenyPermissions(pkg.packageName);
13109                    final boolean permissionViolation =
13110                            deniedPermissions == null || !deniedPermissions.contains(perm);
13111                    if (permissionViolation) {
13112                        if (mPrivappPermissionsViolations == null) {
13113                            mPrivappPermissionsViolations = new ArraySet<>();
13114                        }
13115                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13116                    } else {
13117                        return false;
13118                    }
13119                }
13120                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13121                    return false;
13122                }
13123            }
13124        }
13125        boolean allowed = (compareSignatures(
13126                bp.getSourcePackageSetting().signatures.mSignatures, pkg.mSignatures)
13127                        == PackageManager.SIGNATURE_MATCH)
13128                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13129                        == PackageManager.SIGNATURE_MATCH);
13130        if (!allowed && (privilegedPermission || oemPermission)) {
13131            if (isSystemApp(pkg)) {
13132                // For updated system applications, a privileged/oem permission
13133                // is granted only if it had been defined by the original application.
13134                if (pkg.isUpdatedSystemApp()) {
13135                    final PackageSetting sysPs = mSettings
13136                            .getDisabledSystemPkgLPr(pkg.packageName);
13137                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13138                        // If the original was granted this permission, we take
13139                        // that grant decision as read and propagate it to the
13140                        // update.
13141                        if ((privilegedPermission && sysPs.isPrivileged())
13142                                || (oemPermission && sysPs.isOem()
13143                                        && canGrantOemPermission(sysPs, perm))) {
13144                            allowed = true;
13145                        }
13146                    } else {
13147                        // The system apk may have been updated with an older
13148                        // version of the one on the data partition, but which
13149                        // granted a new system permission that it didn't have
13150                        // before.  In this case we do want to allow the app to
13151                        // now get the new permission if the ancestral apk is
13152                        // privileged to get it.
13153                        if (sysPs != null && sysPs.pkg != null
13154                                && isPackageRequestingPermission(sysPs.pkg, perm)
13155                                && ((privilegedPermission && sysPs.isPrivileged())
13156                                        || (oemPermission && sysPs.isOem()
13157                                                && canGrantOemPermission(sysPs, perm)))) {
13158                            allowed = true;
13159                        }
13160                        // Also if a privileged parent package on the system image or any of
13161                        // its children requested a privileged/oem permission, the updated child
13162                        // packages can also get the permission.
13163                        if (pkg.parentPackage != null) {
13164                            final PackageSetting disabledSysParentPs = mSettings
13165                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13166                            final PackageParser.Package disabledSysParentPkg =
13167                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
13168                                    ? null : disabledSysParentPs.pkg;
13169                            if (disabledSysParentPkg != null
13170                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
13171                                            || (oemPermission && disabledSysParentPs.isOem()))) {
13172                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
13173                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
13174                                    allowed = true;
13175                                } else if (disabledSysParentPkg.childPackages != null) {
13176                                    final int count = disabledSysParentPkg.childPackages.size();
13177                                    for (int i = 0; i < count; i++) {
13178                                        final PackageParser.Package disabledSysChildPkg =
13179                                                disabledSysParentPkg.childPackages.get(i);
13180                                        final PackageSetting disabledSysChildPs =
13181                                                mSettings.getDisabledSystemPkgLPr(
13182                                                        disabledSysChildPkg.packageName);
13183                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
13184                                                && canGrantOemPermission(
13185                                                        disabledSysChildPs, perm)) {
13186                                            allowed = true;
13187                                            break;
13188                                        }
13189                                    }
13190                                }
13191                            }
13192                        }
13193                    }
13194                } else {
13195                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
13196                            || (oemPermission && isOemApp(pkg)
13197                                    && canGrantOemPermission(
13198                                            mSettings.getPackageLPr(pkg.packageName), perm));
13199                }
13200            }
13201        }
13202        if (!allowed) {
13203            if (!allowed
13204                    && bp.isPre23()
13205                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13206                // If this was a previously normal/dangerous permission that got moved
13207                // to a system permission as part of the runtime permission redesign, then
13208                // we still want to blindly grant it to old apps.
13209                allowed = true;
13210            }
13211            if (!allowed && bp.isInstaller()
13212                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13213                // If this permission is to be granted to the system installer and
13214                // this app is an installer, then it gets the permission.
13215                allowed = true;
13216            }
13217            if (!allowed && bp.isVerifier()
13218                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13219                // If this permission is to be granted to the system verifier and
13220                // this app is a verifier, then it gets the permission.
13221                allowed = true;
13222            }
13223            if (!allowed && bp.isPreInstalled()
13224                    && isSystemApp(pkg)) {
13225                // Any pre-installed system app is allowed to get this permission.
13226                allowed = true;
13227            }
13228            if (!allowed && bp.isDevelopment()) {
13229                // For development permissions, a development permission
13230                // is granted only if it was already granted.
13231                allowed = origPermissions.hasInstallPermission(perm);
13232            }
13233            if (!allowed && bp.isSetup()
13234                    && pkg.packageName.equals(mSetupWizardPackage)) {
13235                // If this permission is to be granted to the system setup wizard and
13236                // this app is a setup wizard, then it gets the permission.
13237                allowed = true;
13238            }
13239        }
13240        return allowed;
13241    }
13242
13243    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
13244        if (!ps.isOem()) {
13245            return false;
13246        }
13247        // all oem permissions must explicitly be granted or denied
13248        final Boolean granted =
13249                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
13250        if (granted == null) {
13251            throw new IllegalStateException("OEM permission" + permission + " requested by package "
13252                    + ps.name + " must be explicitly declared granted or not");
13253        }
13254        return Boolean.TRUE == granted;
13255    }
13256
13257    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13258        final int permCount = pkg.requestedPermissions.size();
13259        for (int j = 0; j < permCount; j++) {
13260            String requestedPermission = pkg.requestedPermissions.get(j);
13261            if (permission.equals(requestedPermission)) {
13262                return true;
13263            }
13264        }
13265        return false;
13266    }
13267
13268    final class ActivityIntentResolver
13269            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13270        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13271                boolean defaultOnly, int userId) {
13272            if (!sUserManager.exists(userId)) return null;
13273            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13274            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13275        }
13276
13277        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13278                int userId) {
13279            if (!sUserManager.exists(userId)) return null;
13280            mFlags = flags;
13281            return super.queryIntent(intent, resolvedType,
13282                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13283                    userId);
13284        }
13285
13286        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13287                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13288            if (!sUserManager.exists(userId)) return null;
13289            if (packageActivities == null) {
13290                return null;
13291            }
13292            mFlags = flags;
13293            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13294            final int N = packageActivities.size();
13295            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13296                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13297
13298            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13299            for (int i = 0; i < N; ++i) {
13300                intentFilters = packageActivities.get(i).intents;
13301                if (intentFilters != null && intentFilters.size() > 0) {
13302                    PackageParser.ActivityIntentInfo[] array =
13303                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13304                    intentFilters.toArray(array);
13305                    listCut.add(array);
13306                }
13307            }
13308            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13309        }
13310
13311        /**
13312         * Finds a privileged activity that matches the specified activity names.
13313         */
13314        private PackageParser.Activity findMatchingActivity(
13315                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13316            for (PackageParser.Activity sysActivity : activityList) {
13317                if (sysActivity.info.name.equals(activityInfo.name)) {
13318                    return sysActivity;
13319                }
13320                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13321                    return sysActivity;
13322                }
13323                if (sysActivity.info.targetActivity != null) {
13324                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13325                        return sysActivity;
13326                    }
13327                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13328                        return sysActivity;
13329                    }
13330                }
13331            }
13332            return null;
13333        }
13334
13335        public class IterGenerator<E> {
13336            public Iterator<E> generate(ActivityIntentInfo info) {
13337                return null;
13338            }
13339        }
13340
13341        public class ActionIterGenerator extends IterGenerator<String> {
13342            @Override
13343            public Iterator<String> generate(ActivityIntentInfo info) {
13344                return info.actionsIterator();
13345            }
13346        }
13347
13348        public class CategoriesIterGenerator extends IterGenerator<String> {
13349            @Override
13350            public Iterator<String> generate(ActivityIntentInfo info) {
13351                return info.categoriesIterator();
13352            }
13353        }
13354
13355        public class SchemesIterGenerator extends IterGenerator<String> {
13356            @Override
13357            public Iterator<String> generate(ActivityIntentInfo info) {
13358                return info.schemesIterator();
13359            }
13360        }
13361
13362        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13363            @Override
13364            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13365                return info.authoritiesIterator();
13366            }
13367        }
13368
13369        /**
13370         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13371         * MODIFIED. Do not pass in a list that should not be changed.
13372         */
13373        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13374                IterGenerator<T> generator, Iterator<T> searchIterator) {
13375            // loop through the set of actions; every one must be found in the intent filter
13376            while (searchIterator.hasNext()) {
13377                // we must have at least one filter in the list to consider a match
13378                if (intentList.size() == 0) {
13379                    break;
13380                }
13381
13382                final T searchAction = searchIterator.next();
13383
13384                // loop through the set of intent filters
13385                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13386                while (intentIter.hasNext()) {
13387                    final ActivityIntentInfo intentInfo = intentIter.next();
13388                    boolean selectionFound = false;
13389
13390                    // loop through the intent filter's selection criteria; at least one
13391                    // of them must match the searched criteria
13392                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13393                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13394                        final T intentSelection = intentSelectionIter.next();
13395                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13396                            selectionFound = true;
13397                            break;
13398                        }
13399                    }
13400
13401                    // the selection criteria wasn't found in this filter's set; this filter
13402                    // is not a potential match
13403                    if (!selectionFound) {
13404                        intentIter.remove();
13405                    }
13406                }
13407            }
13408        }
13409
13410        private boolean isProtectedAction(ActivityIntentInfo filter) {
13411            final Iterator<String> actionsIter = filter.actionsIterator();
13412            while (actionsIter != null && actionsIter.hasNext()) {
13413                final String filterAction = actionsIter.next();
13414                if (PROTECTED_ACTIONS.contains(filterAction)) {
13415                    return true;
13416                }
13417            }
13418            return false;
13419        }
13420
13421        /**
13422         * Adjusts the priority of the given intent filter according to policy.
13423         * <p>
13424         * <ul>
13425         * <li>The priority for non privileged applications is capped to '0'</li>
13426         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13427         * <li>The priority for unbundled updates to privileged applications is capped to the
13428         *      priority defined on the system partition</li>
13429         * </ul>
13430         * <p>
13431         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13432         * allowed to obtain any priority on any action.
13433         */
13434        private void adjustPriority(
13435                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13436            // nothing to do; priority is fine as-is
13437            if (intent.getPriority() <= 0) {
13438                return;
13439            }
13440
13441            final ActivityInfo activityInfo = intent.activity.info;
13442            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13443
13444            final boolean privilegedApp =
13445                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13446            if (!privilegedApp) {
13447                // non-privileged applications can never define a priority >0
13448                if (DEBUG_FILTERS) {
13449                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13450                            + " package: " + applicationInfo.packageName
13451                            + " activity: " + intent.activity.className
13452                            + " origPrio: " + intent.getPriority());
13453                }
13454                intent.setPriority(0);
13455                return;
13456            }
13457
13458            if (systemActivities == null) {
13459                // the system package is not disabled; we're parsing the system partition
13460                if (isProtectedAction(intent)) {
13461                    if (mDeferProtectedFilters) {
13462                        // We can't deal with these just yet. No component should ever obtain a
13463                        // >0 priority for a protected actions, with ONE exception -- the setup
13464                        // wizard. The setup wizard, however, cannot be known until we're able to
13465                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13466                        // until all intent filters have been processed. Chicken, meet egg.
13467                        // Let the filter temporarily have a high priority and rectify the
13468                        // priorities after all system packages have been scanned.
13469                        mProtectedFilters.add(intent);
13470                        if (DEBUG_FILTERS) {
13471                            Slog.i(TAG, "Protected action; save for later;"
13472                                    + " package: " + applicationInfo.packageName
13473                                    + " activity: " + intent.activity.className
13474                                    + " origPrio: " + intent.getPriority());
13475                        }
13476                        return;
13477                    } else {
13478                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13479                            Slog.i(TAG, "No setup wizard;"
13480                                + " All protected intents capped to priority 0");
13481                        }
13482                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13483                            if (DEBUG_FILTERS) {
13484                                Slog.i(TAG, "Found setup wizard;"
13485                                    + " allow priority " + intent.getPriority() + ";"
13486                                    + " package: " + intent.activity.info.packageName
13487                                    + " activity: " + intent.activity.className
13488                                    + " priority: " + intent.getPriority());
13489                            }
13490                            // setup wizard gets whatever it wants
13491                            return;
13492                        }
13493                        if (DEBUG_FILTERS) {
13494                            Slog.i(TAG, "Protected action; cap priority to 0;"
13495                                    + " package: " + intent.activity.info.packageName
13496                                    + " activity: " + intent.activity.className
13497                                    + " origPrio: " + intent.getPriority());
13498                        }
13499                        intent.setPriority(0);
13500                        return;
13501                    }
13502                }
13503                // privileged apps on the system image get whatever priority they request
13504                return;
13505            }
13506
13507            // privileged app unbundled update ... try to find the same activity
13508            final PackageParser.Activity foundActivity =
13509                    findMatchingActivity(systemActivities, activityInfo);
13510            if (foundActivity == null) {
13511                // this is a new activity; it cannot obtain >0 priority
13512                if (DEBUG_FILTERS) {
13513                    Slog.i(TAG, "New activity; cap priority to 0;"
13514                            + " package: " + applicationInfo.packageName
13515                            + " activity: " + intent.activity.className
13516                            + " origPrio: " + intent.getPriority());
13517                }
13518                intent.setPriority(0);
13519                return;
13520            }
13521
13522            // found activity, now check for filter equivalence
13523
13524            // a shallow copy is enough; we modify the list, not its contents
13525            final List<ActivityIntentInfo> intentListCopy =
13526                    new ArrayList<>(foundActivity.intents);
13527            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13528
13529            // find matching action subsets
13530            final Iterator<String> actionsIterator = intent.actionsIterator();
13531            if (actionsIterator != null) {
13532                getIntentListSubset(
13533                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13534                if (intentListCopy.size() == 0) {
13535                    // no more intents to match; we're not equivalent
13536                    if (DEBUG_FILTERS) {
13537                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13538                                + " package: " + applicationInfo.packageName
13539                                + " activity: " + intent.activity.className
13540                                + " origPrio: " + intent.getPriority());
13541                    }
13542                    intent.setPriority(0);
13543                    return;
13544                }
13545            }
13546
13547            // find matching category subsets
13548            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13549            if (categoriesIterator != null) {
13550                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13551                        categoriesIterator);
13552                if (intentListCopy.size() == 0) {
13553                    // no more intents to match; we're not equivalent
13554                    if (DEBUG_FILTERS) {
13555                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13556                                + " package: " + applicationInfo.packageName
13557                                + " activity: " + intent.activity.className
13558                                + " origPrio: " + intent.getPriority());
13559                    }
13560                    intent.setPriority(0);
13561                    return;
13562                }
13563            }
13564
13565            // find matching schemes subsets
13566            final Iterator<String> schemesIterator = intent.schemesIterator();
13567            if (schemesIterator != null) {
13568                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13569                        schemesIterator);
13570                if (intentListCopy.size() == 0) {
13571                    // no more intents to match; we're not equivalent
13572                    if (DEBUG_FILTERS) {
13573                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13574                                + " package: " + applicationInfo.packageName
13575                                + " activity: " + intent.activity.className
13576                                + " origPrio: " + intent.getPriority());
13577                    }
13578                    intent.setPriority(0);
13579                    return;
13580                }
13581            }
13582
13583            // find matching authorities subsets
13584            final Iterator<IntentFilter.AuthorityEntry>
13585                    authoritiesIterator = intent.authoritiesIterator();
13586            if (authoritiesIterator != null) {
13587                getIntentListSubset(intentListCopy,
13588                        new AuthoritiesIterGenerator(),
13589                        authoritiesIterator);
13590                if (intentListCopy.size() == 0) {
13591                    // no more intents to match; we're not equivalent
13592                    if (DEBUG_FILTERS) {
13593                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13594                                + " package: " + applicationInfo.packageName
13595                                + " activity: " + intent.activity.className
13596                                + " origPrio: " + intent.getPriority());
13597                    }
13598                    intent.setPriority(0);
13599                    return;
13600                }
13601            }
13602
13603            // we found matching filter(s); app gets the max priority of all intents
13604            int cappedPriority = 0;
13605            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13606                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13607            }
13608            if (intent.getPriority() > cappedPriority) {
13609                if (DEBUG_FILTERS) {
13610                    Slog.i(TAG, "Found matching filter(s);"
13611                            + " cap priority to " + cappedPriority + ";"
13612                            + " package: " + applicationInfo.packageName
13613                            + " activity: " + intent.activity.className
13614                            + " origPrio: " + intent.getPriority());
13615                }
13616                intent.setPriority(cappedPriority);
13617                return;
13618            }
13619            // all this for nothing; the requested priority was <= what was on the system
13620        }
13621
13622        public final void addActivity(PackageParser.Activity a, String type) {
13623            mActivities.put(a.getComponentName(), a);
13624            if (DEBUG_SHOW_INFO)
13625                Log.v(
13626                TAG, "  " + type + " " +
13627                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13628            if (DEBUG_SHOW_INFO)
13629                Log.v(TAG, "    Class=" + a.info.name);
13630            final int NI = a.intents.size();
13631            for (int j=0; j<NI; j++) {
13632                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13633                if ("activity".equals(type)) {
13634                    final PackageSetting ps =
13635                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13636                    final List<PackageParser.Activity> systemActivities =
13637                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13638                    adjustPriority(systemActivities, intent);
13639                }
13640                if (DEBUG_SHOW_INFO) {
13641                    Log.v(TAG, "    IntentFilter:");
13642                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13643                }
13644                if (!intent.debugCheck()) {
13645                    Log.w(TAG, "==> For Activity " + a.info.name);
13646                }
13647                addFilter(intent);
13648            }
13649        }
13650
13651        public final void removeActivity(PackageParser.Activity a, String type) {
13652            mActivities.remove(a.getComponentName());
13653            if (DEBUG_SHOW_INFO) {
13654                Log.v(TAG, "  " + type + " "
13655                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13656                                : a.info.name) + ":");
13657                Log.v(TAG, "    Class=" + a.info.name);
13658            }
13659            final int NI = a.intents.size();
13660            for (int j=0; j<NI; j++) {
13661                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13662                if (DEBUG_SHOW_INFO) {
13663                    Log.v(TAG, "    IntentFilter:");
13664                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13665                }
13666                removeFilter(intent);
13667            }
13668        }
13669
13670        @Override
13671        protected boolean allowFilterResult(
13672                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13673            ActivityInfo filterAi = filter.activity.info;
13674            for (int i=dest.size()-1; i>=0; i--) {
13675                ActivityInfo destAi = dest.get(i).activityInfo;
13676                if (destAi.name == filterAi.name
13677                        && destAi.packageName == filterAi.packageName) {
13678                    return false;
13679                }
13680            }
13681            return true;
13682        }
13683
13684        @Override
13685        protected ActivityIntentInfo[] newArray(int size) {
13686            return new ActivityIntentInfo[size];
13687        }
13688
13689        @Override
13690        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13691            if (!sUserManager.exists(userId)) return true;
13692            PackageParser.Package p = filter.activity.owner;
13693            if (p != null) {
13694                PackageSetting ps = (PackageSetting)p.mExtras;
13695                if (ps != null) {
13696                    // System apps are never considered stopped for purposes of
13697                    // filtering, because there may be no way for the user to
13698                    // actually re-launch them.
13699                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13700                            && ps.getStopped(userId);
13701                }
13702            }
13703            return false;
13704        }
13705
13706        @Override
13707        protected boolean isPackageForFilter(String packageName,
13708                PackageParser.ActivityIntentInfo info) {
13709            return packageName.equals(info.activity.owner.packageName);
13710        }
13711
13712        @Override
13713        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13714                int match, int userId) {
13715            if (!sUserManager.exists(userId)) return null;
13716            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13717                return null;
13718            }
13719            final PackageParser.Activity activity = info.activity;
13720            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13721            if (ps == null) {
13722                return null;
13723            }
13724            final PackageUserState userState = ps.readUserState(userId);
13725            ActivityInfo ai =
13726                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13727            if (ai == null) {
13728                return null;
13729            }
13730            final boolean matchExplicitlyVisibleOnly =
13731                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13732            final boolean matchVisibleToInstantApp =
13733                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13734            final boolean componentVisible =
13735                    matchVisibleToInstantApp
13736                    && info.isVisibleToInstantApp()
13737                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13738            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13739            // throw out filters that aren't visible to ephemeral apps
13740            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13741                return null;
13742            }
13743            // throw out instant app filters if we're not explicitly requesting them
13744            if (!matchInstantApp && userState.instantApp) {
13745                return null;
13746            }
13747            // throw out instant app filters if updates are available; will trigger
13748            // instant app resolution
13749            if (userState.instantApp && ps.isUpdateAvailable()) {
13750                return null;
13751            }
13752            final ResolveInfo res = new ResolveInfo();
13753            res.activityInfo = ai;
13754            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13755                res.filter = info;
13756            }
13757            if (info != null) {
13758                res.handleAllWebDataURI = info.handleAllWebDataURI();
13759            }
13760            res.priority = info.getPriority();
13761            res.preferredOrder = activity.owner.mPreferredOrder;
13762            //System.out.println("Result: " + res.activityInfo.className +
13763            //                   " = " + res.priority);
13764            res.match = match;
13765            res.isDefault = info.hasDefault;
13766            res.labelRes = info.labelRes;
13767            res.nonLocalizedLabel = info.nonLocalizedLabel;
13768            if (userNeedsBadging(userId)) {
13769                res.noResourceId = true;
13770            } else {
13771                res.icon = info.icon;
13772            }
13773            res.iconResourceId = info.icon;
13774            res.system = res.activityInfo.applicationInfo.isSystemApp();
13775            res.isInstantAppAvailable = userState.instantApp;
13776            return res;
13777        }
13778
13779        @Override
13780        protected void sortResults(List<ResolveInfo> results) {
13781            Collections.sort(results, mResolvePrioritySorter);
13782        }
13783
13784        @Override
13785        protected void dumpFilter(PrintWriter out, String prefix,
13786                PackageParser.ActivityIntentInfo filter) {
13787            out.print(prefix); out.print(
13788                    Integer.toHexString(System.identityHashCode(filter.activity)));
13789                    out.print(' ');
13790                    filter.activity.printComponentShortName(out);
13791                    out.print(" filter ");
13792                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13793        }
13794
13795        @Override
13796        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13797            return filter.activity;
13798        }
13799
13800        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13801            PackageParser.Activity activity = (PackageParser.Activity)label;
13802            out.print(prefix); out.print(
13803                    Integer.toHexString(System.identityHashCode(activity)));
13804                    out.print(' ');
13805                    activity.printComponentShortName(out);
13806            if (count > 1) {
13807                out.print(" ("); out.print(count); out.print(" filters)");
13808            }
13809            out.println();
13810        }
13811
13812        // Keys are String (activity class name), values are Activity.
13813        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13814                = new ArrayMap<ComponentName, PackageParser.Activity>();
13815        private int mFlags;
13816    }
13817
13818    private final class ServiceIntentResolver
13819            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13820        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13821                boolean defaultOnly, int userId) {
13822            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13823            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13824        }
13825
13826        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13827                int userId) {
13828            if (!sUserManager.exists(userId)) return null;
13829            mFlags = flags;
13830            return super.queryIntent(intent, resolvedType,
13831                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13832                    userId);
13833        }
13834
13835        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13836                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13837            if (!sUserManager.exists(userId)) return null;
13838            if (packageServices == null) {
13839                return null;
13840            }
13841            mFlags = flags;
13842            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13843            final int N = packageServices.size();
13844            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13845                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13846
13847            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13848            for (int i = 0; i < N; ++i) {
13849                intentFilters = packageServices.get(i).intents;
13850                if (intentFilters != null && intentFilters.size() > 0) {
13851                    PackageParser.ServiceIntentInfo[] array =
13852                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13853                    intentFilters.toArray(array);
13854                    listCut.add(array);
13855                }
13856            }
13857            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13858        }
13859
13860        public final void addService(PackageParser.Service s) {
13861            mServices.put(s.getComponentName(), s);
13862            if (DEBUG_SHOW_INFO) {
13863                Log.v(TAG, "  "
13864                        + (s.info.nonLocalizedLabel != null
13865                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13866                Log.v(TAG, "    Class=" + s.info.name);
13867            }
13868            final int NI = s.intents.size();
13869            int j;
13870            for (j=0; j<NI; j++) {
13871                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13872                if (DEBUG_SHOW_INFO) {
13873                    Log.v(TAG, "    IntentFilter:");
13874                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13875                }
13876                if (!intent.debugCheck()) {
13877                    Log.w(TAG, "==> For Service " + s.info.name);
13878                }
13879                addFilter(intent);
13880            }
13881        }
13882
13883        public final void removeService(PackageParser.Service s) {
13884            mServices.remove(s.getComponentName());
13885            if (DEBUG_SHOW_INFO) {
13886                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13887                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13888                Log.v(TAG, "    Class=" + s.info.name);
13889            }
13890            final int NI = s.intents.size();
13891            int j;
13892            for (j=0; j<NI; j++) {
13893                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13894                if (DEBUG_SHOW_INFO) {
13895                    Log.v(TAG, "    IntentFilter:");
13896                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13897                }
13898                removeFilter(intent);
13899            }
13900        }
13901
13902        @Override
13903        protected boolean allowFilterResult(
13904                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13905            ServiceInfo filterSi = filter.service.info;
13906            for (int i=dest.size()-1; i>=0; i--) {
13907                ServiceInfo destAi = dest.get(i).serviceInfo;
13908                if (destAi.name == filterSi.name
13909                        && destAi.packageName == filterSi.packageName) {
13910                    return false;
13911                }
13912            }
13913            return true;
13914        }
13915
13916        @Override
13917        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13918            return new PackageParser.ServiceIntentInfo[size];
13919        }
13920
13921        @Override
13922        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13923            if (!sUserManager.exists(userId)) return true;
13924            PackageParser.Package p = filter.service.owner;
13925            if (p != null) {
13926                PackageSetting ps = (PackageSetting)p.mExtras;
13927                if (ps != null) {
13928                    // System apps are never considered stopped for purposes of
13929                    // filtering, because there may be no way for the user to
13930                    // actually re-launch them.
13931                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13932                            && ps.getStopped(userId);
13933                }
13934            }
13935            return false;
13936        }
13937
13938        @Override
13939        protected boolean isPackageForFilter(String packageName,
13940                PackageParser.ServiceIntentInfo info) {
13941            return packageName.equals(info.service.owner.packageName);
13942        }
13943
13944        @Override
13945        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13946                int match, int userId) {
13947            if (!sUserManager.exists(userId)) return null;
13948            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13949            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13950                return null;
13951            }
13952            final PackageParser.Service service = info.service;
13953            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13954            if (ps == null) {
13955                return null;
13956            }
13957            final PackageUserState userState = ps.readUserState(userId);
13958            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13959                    userState, userId);
13960            if (si == null) {
13961                return null;
13962            }
13963            final boolean matchVisibleToInstantApp =
13964                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13965            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13966            // throw out filters that aren't visible to ephemeral apps
13967            if (matchVisibleToInstantApp
13968                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13969                return null;
13970            }
13971            // throw out ephemeral filters if we're not explicitly requesting them
13972            if (!isInstantApp && userState.instantApp) {
13973                return null;
13974            }
13975            // throw out instant app filters if updates are available; will trigger
13976            // instant app resolution
13977            if (userState.instantApp && ps.isUpdateAvailable()) {
13978                return null;
13979            }
13980            final ResolveInfo res = new ResolveInfo();
13981            res.serviceInfo = si;
13982            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13983                res.filter = filter;
13984            }
13985            res.priority = info.getPriority();
13986            res.preferredOrder = service.owner.mPreferredOrder;
13987            res.match = match;
13988            res.isDefault = info.hasDefault;
13989            res.labelRes = info.labelRes;
13990            res.nonLocalizedLabel = info.nonLocalizedLabel;
13991            res.icon = info.icon;
13992            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13993            return res;
13994        }
13995
13996        @Override
13997        protected void sortResults(List<ResolveInfo> results) {
13998            Collections.sort(results, mResolvePrioritySorter);
13999        }
14000
14001        @Override
14002        protected void dumpFilter(PrintWriter out, String prefix,
14003                PackageParser.ServiceIntentInfo filter) {
14004            out.print(prefix); out.print(
14005                    Integer.toHexString(System.identityHashCode(filter.service)));
14006                    out.print(' ');
14007                    filter.service.printComponentShortName(out);
14008                    out.print(" filter ");
14009                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14010        }
14011
14012        @Override
14013        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14014            return filter.service;
14015        }
14016
14017        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14018            PackageParser.Service service = (PackageParser.Service)label;
14019            out.print(prefix); out.print(
14020                    Integer.toHexString(System.identityHashCode(service)));
14021                    out.print(' ');
14022                    service.printComponentShortName(out);
14023            if (count > 1) {
14024                out.print(" ("); out.print(count); out.print(" filters)");
14025            }
14026            out.println();
14027        }
14028
14029//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14030//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14031//            final List<ResolveInfo> retList = Lists.newArrayList();
14032//            while (i.hasNext()) {
14033//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14034//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14035//                    retList.add(resolveInfo);
14036//                }
14037//            }
14038//            return retList;
14039//        }
14040
14041        // Keys are String (activity class name), values are Activity.
14042        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14043                = new ArrayMap<ComponentName, PackageParser.Service>();
14044        private int mFlags;
14045    }
14046
14047    private final class ProviderIntentResolver
14048            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14049        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14050                boolean defaultOnly, int userId) {
14051            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14052            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14053        }
14054
14055        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14056                int userId) {
14057            if (!sUserManager.exists(userId))
14058                return null;
14059            mFlags = flags;
14060            return super.queryIntent(intent, resolvedType,
14061                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14062                    userId);
14063        }
14064
14065        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14066                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14067            if (!sUserManager.exists(userId))
14068                return null;
14069            if (packageProviders == null) {
14070                return null;
14071            }
14072            mFlags = flags;
14073            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14074            final int N = packageProviders.size();
14075            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14076                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14077
14078            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14079            for (int i = 0; i < N; ++i) {
14080                intentFilters = packageProviders.get(i).intents;
14081                if (intentFilters != null && intentFilters.size() > 0) {
14082                    PackageParser.ProviderIntentInfo[] array =
14083                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14084                    intentFilters.toArray(array);
14085                    listCut.add(array);
14086                }
14087            }
14088            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14089        }
14090
14091        public final void addProvider(PackageParser.Provider p) {
14092            if (mProviders.containsKey(p.getComponentName())) {
14093                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14094                return;
14095            }
14096
14097            mProviders.put(p.getComponentName(), p);
14098            if (DEBUG_SHOW_INFO) {
14099                Log.v(TAG, "  "
14100                        + (p.info.nonLocalizedLabel != null
14101                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14102                Log.v(TAG, "    Class=" + p.info.name);
14103            }
14104            final int NI = p.intents.size();
14105            int j;
14106            for (j = 0; j < NI; j++) {
14107                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14108                if (DEBUG_SHOW_INFO) {
14109                    Log.v(TAG, "    IntentFilter:");
14110                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14111                }
14112                if (!intent.debugCheck()) {
14113                    Log.w(TAG, "==> For Provider " + p.info.name);
14114                }
14115                addFilter(intent);
14116            }
14117        }
14118
14119        public final void removeProvider(PackageParser.Provider p) {
14120            mProviders.remove(p.getComponentName());
14121            if (DEBUG_SHOW_INFO) {
14122                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14123                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14124                Log.v(TAG, "    Class=" + p.info.name);
14125            }
14126            final int NI = p.intents.size();
14127            int j;
14128            for (j = 0; j < NI; j++) {
14129                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14130                if (DEBUG_SHOW_INFO) {
14131                    Log.v(TAG, "    IntentFilter:");
14132                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14133                }
14134                removeFilter(intent);
14135            }
14136        }
14137
14138        @Override
14139        protected boolean allowFilterResult(
14140                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14141            ProviderInfo filterPi = filter.provider.info;
14142            for (int i = dest.size() - 1; i >= 0; i--) {
14143                ProviderInfo destPi = dest.get(i).providerInfo;
14144                if (destPi.name == filterPi.name
14145                        && destPi.packageName == filterPi.packageName) {
14146                    return false;
14147                }
14148            }
14149            return true;
14150        }
14151
14152        @Override
14153        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14154            return new PackageParser.ProviderIntentInfo[size];
14155        }
14156
14157        @Override
14158        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14159            if (!sUserManager.exists(userId))
14160                return true;
14161            PackageParser.Package p = filter.provider.owner;
14162            if (p != null) {
14163                PackageSetting ps = (PackageSetting) p.mExtras;
14164                if (ps != null) {
14165                    // System apps are never considered stopped for purposes of
14166                    // filtering, because there may be no way for the user to
14167                    // actually re-launch them.
14168                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14169                            && ps.getStopped(userId);
14170                }
14171            }
14172            return false;
14173        }
14174
14175        @Override
14176        protected boolean isPackageForFilter(String packageName,
14177                PackageParser.ProviderIntentInfo info) {
14178            return packageName.equals(info.provider.owner.packageName);
14179        }
14180
14181        @Override
14182        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14183                int match, int userId) {
14184            if (!sUserManager.exists(userId))
14185                return null;
14186            final PackageParser.ProviderIntentInfo info = filter;
14187            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14188                return null;
14189            }
14190            final PackageParser.Provider provider = info.provider;
14191            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14192            if (ps == null) {
14193                return null;
14194            }
14195            final PackageUserState userState = ps.readUserState(userId);
14196            final boolean matchVisibleToInstantApp =
14197                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14198            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14199            // throw out filters that aren't visible to instant applications
14200            if (matchVisibleToInstantApp
14201                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14202                return null;
14203            }
14204            // throw out instant application filters if we're not explicitly requesting them
14205            if (!isInstantApp && userState.instantApp) {
14206                return null;
14207            }
14208            // throw out instant application filters if updates are available; will trigger
14209            // instant application resolution
14210            if (userState.instantApp && ps.isUpdateAvailable()) {
14211                return null;
14212            }
14213            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14214                    userState, userId);
14215            if (pi == null) {
14216                return null;
14217            }
14218            final ResolveInfo res = new ResolveInfo();
14219            res.providerInfo = pi;
14220            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14221                res.filter = filter;
14222            }
14223            res.priority = info.getPriority();
14224            res.preferredOrder = provider.owner.mPreferredOrder;
14225            res.match = match;
14226            res.isDefault = info.hasDefault;
14227            res.labelRes = info.labelRes;
14228            res.nonLocalizedLabel = info.nonLocalizedLabel;
14229            res.icon = info.icon;
14230            res.system = res.providerInfo.applicationInfo.isSystemApp();
14231            return res;
14232        }
14233
14234        @Override
14235        protected void sortResults(List<ResolveInfo> results) {
14236            Collections.sort(results, mResolvePrioritySorter);
14237        }
14238
14239        @Override
14240        protected void dumpFilter(PrintWriter out, String prefix,
14241                PackageParser.ProviderIntentInfo filter) {
14242            out.print(prefix);
14243            out.print(
14244                    Integer.toHexString(System.identityHashCode(filter.provider)));
14245            out.print(' ');
14246            filter.provider.printComponentShortName(out);
14247            out.print(" filter ");
14248            out.println(Integer.toHexString(System.identityHashCode(filter)));
14249        }
14250
14251        @Override
14252        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14253            return filter.provider;
14254        }
14255
14256        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14257            PackageParser.Provider provider = (PackageParser.Provider)label;
14258            out.print(prefix); out.print(
14259                    Integer.toHexString(System.identityHashCode(provider)));
14260                    out.print(' ');
14261                    provider.printComponentShortName(out);
14262            if (count > 1) {
14263                out.print(" ("); out.print(count); out.print(" filters)");
14264            }
14265            out.println();
14266        }
14267
14268        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14269                = new ArrayMap<ComponentName, PackageParser.Provider>();
14270        private int mFlags;
14271    }
14272
14273    static final class EphemeralIntentResolver
14274            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14275        /**
14276         * The result that has the highest defined order. Ordering applies on a
14277         * per-package basis. Mapping is from package name to Pair of order and
14278         * EphemeralResolveInfo.
14279         * <p>
14280         * NOTE: This is implemented as a field variable for convenience and efficiency.
14281         * By having a field variable, we're able to track filter ordering as soon as
14282         * a non-zero order is defined. Otherwise, multiple loops across the result set
14283         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14284         * this needs to be contained entirely within {@link #filterResults}.
14285         */
14286        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14287
14288        @Override
14289        protected AuxiliaryResolveInfo[] newArray(int size) {
14290            return new AuxiliaryResolveInfo[size];
14291        }
14292
14293        @Override
14294        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14295            return true;
14296        }
14297
14298        @Override
14299        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14300                int userId) {
14301            if (!sUserManager.exists(userId)) {
14302                return null;
14303            }
14304            final String packageName = responseObj.resolveInfo.getPackageName();
14305            final Integer order = responseObj.getOrder();
14306            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14307                    mOrderResult.get(packageName);
14308            // ordering is enabled and this item's order isn't high enough
14309            if (lastOrderResult != null && lastOrderResult.first >= order) {
14310                return null;
14311            }
14312            final InstantAppResolveInfo res = responseObj.resolveInfo;
14313            if (order > 0) {
14314                // non-zero order, enable ordering
14315                mOrderResult.put(packageName, new Pair<>(order, res));
14316            }
14317            return responseObj;
14318        }
14319
14320        @Override
14321        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14322            // only do work if ordering is enabled [most of the time it won't be]
14323            if (mOrderResult.size() == 0) {
14324                return;
14325            }
14326            int resultSize = results.size();
14327            for (int i = 0; i < resultSize; i++) {
14328                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14329                final String packageName = info.getPackageName();
14330                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14331                if (savedInfo == null) {
14332                    // package doesn't having ordering
14333                    continue;
14334                }
14335                if (savedInfo.second == info) {
14336                    // circled back to the highest ordered item; remove from order list
14337                    mOrderResult.remove(packageName);
14338                    if (mOrderResult.size() == 0) {
14339                        // no more ordered items
14340                        break;
14341                    }
14342                    continue;
14343                }
14344                // item has a worse order, remove it from the result list
14345                results.remove(i);
14346                resultSize--;
14347                i--;
14348            }
14349        }
14350    }
14351
14352    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14353            new Comparator<ResolveInfo>() {
14354        public int compare(ResolveInfo r1, ResolveInfo r2) {
14355            int v1 = r1.priority;
14356            int v2 = r2.priority;
14357            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14358            if (v1 != v2) {
14359                return (v1 > v2) ? -1 : 1;
14360            }
14361            v1 = r1.preferredOrder;
14362            v2 = r2.preferredOrder;
14363            if (v1 != v2) {
14364                return (v1 > v2) ? -1 : 1;
14365            }
14366            if (r1.isDefault != r2.isDefault) {
14367                return r1.isDefault ? -1 : 1;
14368            }
14369            v1 = r1.match;
14370            v2 = r2.match;
14371            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14372            if (v1 != v2) {
14373                return (v1 > v2) ? -1 : 1;
14374            }
14375            if (r1.system != r2.system) {
14376                return r1.system ? -1 : 1;
14377            }
14378            if (r1.activityInfo != null) {
14379                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14380            }
14381            if (r1.serviceInfo != null) {
14382                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14383            }
14384            if (r1.providerInfo != null) {
14385                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14386            }
14387            return 0;
14388        }
14389    };
14390
14391    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14392            new Comparator<ProviderInfo>() {
14393        public int compare(ProviderInfo p1, ProviderInfo p2) {
14394            final int v1 = p1.initOrder;
14395            final int v2 = p2.initOrder;
14396            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14397        }
14398    };
14399
14400    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14401            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14402            final int[] userIds) {
14403        mHandler.post(new Runnable() {
14404            @Override
14405            public void run() {
14406                try {
14407                    final IActivityManager am = ActivityManager.getService();
14408                    if (am == null) return;
14409                    final int[] resolvedUserIds;
14410                    if (userIds == null) {
14411                        resolvedUserIds = am.getRunningUserIds();
14412                    } else {
14413                        resolvedUserIds = userIds;
14414                    }
14415                    for (int id : resolvedUserIds) {
14416                        final Intent intent = new Intent(action,
14417                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14418                        if (extras != null) {
14419                            intent.putExtras(extras);
14420                        }
14421                        if (targetPkg != null) {
14422                            intent.setPackage(targetPkg);
14423                        }
14424                        // Modify the UID when posting to other users
14425                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14426                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14427                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14428                            intent.putExtra(Intent.EXTRA_UID, uid);
14429                        }
14430                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14431                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14432                        if (DEBUG_BROADCASTS) {
14433                            RuntimeException here = new RuntimeException("here");
14434                            here.fillInStackTrace();
14435                            Slog.d(TAG, "Sending to user " + id + ": "
14436                                    + intent.toShortString(false, true, false, false)
14437                                    + " " + intent.getExtras(), here);
14438                        }
14439                        am.broadcastIntent(null, intent, null, finishedReceiver,
14440                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14441                                null, finishedReceiver != null, false, id);
14442                    }
14443                } catch (RemoteException ex) {
14444                }
14445            }
14446        });
14447    }
14448
14449    /**
14450     * Check if the external storage media is available. This is true if there
14451     * is a mounted external storage medium or if the external storage is
14452     * emulated.
14453     */
14454    private boolean isExternalMediaAvailable() {
14455        return mMediaMounted || Environment.isExternalStorageEmulated();
14456    }
14457
14458    @Override
14459    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14460        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14461            return null;
14462        }
14463        // writer
14464        synchronized (mPackages) {
14465            if (!isExternalMediaAvailable()) {
14466                // If the external storage is no longer mounted at this point,
14467                // the caller may not have been able to delete all of this
14468                // packages files and can not delete any more.  Bail.
14469                return null;
14470            }
14471            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14472            if (lastPackage != null) {
14473                pkgs.remove(lastPackage);
14474            }
14475            if (pkgs.size() > 0) {
14476                return pkgs.get(0);
14477            }
14478        }
14479        return null;
14480    }
14481
14482    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14483        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14484                userId, andCode ? 1 : 0, packageName);
14485        if (mSystemReady) {
14486            msg.sendToTarget();
14487        } else {
14488            if (mPostSystemReadyMessages == null) {
14489                mPostSystemReadyMessages = new ArrayList<>();
14490            }
14491            mPostSystemReadyMessages.add(msg);
14492        }
14493    }
14494
14495    void startCleaningPackages() {
14496        // reader
14497        if (!isExternalMediaAvailable()) {
14498            return;
14499        }
14500        synchronized (mPackages) {
14501            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14502                return;
14503            }
14504        }
14505        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14506        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14507        IActivityManager am = ActivityManager.getService();
14508        if (am != null) {
14509            int dcsUid = -1;
14510            synchronized (mPackages) {
14511                if (!mDefaultContainerWhitelisted) {
14512                    mDefaultContainerWhitelisted = true;
14513                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14514                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14515                }
14516            }
14517            try {
14518                if (dcsUid > 0) {
14519                    am.backgroundWhitelistUid(dcsUid);
14520                }
14521                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14522                        UserHandle.USER_SYSTEM);
14523            } catch (RemoteException e) {
14524            }
14525        }
14526    }
14527
14528    @Override
14529    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14530            int installFlags, String installerPackageName, int userId) {
14531        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14532
14533        final int callingUid = Binder.getCallingUid();
14534        enforceCrossUserPermission(callingUid, userId,
14535                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14536
14537        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14538            try {
14539                if (observer != null) {
14540                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14541                }
14542            } catch (RemoteException re) {
14543            }
14544            return;
14545        }
14546
14547        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14548            installFlags |= PackageManager.INSTALL_FROM_ADB;
14549
14550        } else {
14551            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14552            // about installerPackageName.
14553
14554            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14555            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14556        }
14557
14558        UserHandle user;
14559        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14560            user = UserHandle.ALL;
14561        } else {
14562            user = new UserHandle(userId);
14563        }
14564
14565        // Only system components can circumvent runtime permissions when installing.
14566        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14567                && mContext.checkCallingOrSelfPermission(Manifest.permission
14568                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14569            throw new SecurityException("You need the "
14570                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14571                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14572        }
14573
14574        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14575                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14576            throw new IllegalArgumentException(
14577                    "New installs into ASEC containers no longer supported");
14578        }
14579
14580        final File originFile = new File(originPath);
14581        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14582
14583        final Message msg = mHandler.obtainMessage(INIT_COPY);
14584        final VerificationInfo verificationInfo = new VerificationInfo(
14585                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14586        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14587                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14588                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14589                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14590        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14591        msg.obj = params;
14592
14593        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14594                System.identityHashCode(msg.obj));
14595        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14596                System.identityHashCode(msg.obj));
14597
14598        mHandler.sendMessage(msg);
14599    }
14600
14601
14602    /**
14603     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14604     * it is acting on behalf on an enterprise or the user).
14605     *
14606     * Note that the ordering of the conditionals in this method is important. The checks we perform
14607     * are as follows, in this order:
14608     *
14609     * 1) If the install is being performed by a system app, we can trust the app to have set the
14610     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14611     *    what it is.
14612     * 2) If the install is being performed by a device or profile owner app, the install reason
14613     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14614     *    set the install reason correctly. If the app targets an older SDK version where install
14615     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14616     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14617     * 3) In all other cases, the install is being performed by a regular app that is neither part
14618     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14619     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14620     *    set to enterprise policy and if so, change it to unknown instead.
14621     */
14622    private int fixUpInstallReason(String installerPackageName, int installerUid,
14623            int installReason) {
14624        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14625                == PERMISSION_GRANTED) {
14626            // If the install is being performed by a system app, we trust that app to have set the
14627            // install reason correctly.
14628            return installReason;
14629        }
14630
14631        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14632            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14633        if (dpm != null) {
14634            ComponentName owner = null;
14635            try {
14636                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14637                if (owner == null) {
14638                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14639                }
14640            } catch (RemoteException e) {
14641            }
14642            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14643                // If the install is being performed by a device or profile owner, the install
14644                // reason should be enterprise policy.
14645                return PackageManager.INSTALL_REASON_POLICY;
14646            }
14647        }
14648
14649        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14650            // If the install is being performed by a regular app (i.e. neither system app nor
14651            // device or profile owner), we have no reason to believe that the app is acting on
14652            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14653            // change it to unknown instead.
14654            return PackageManager.INSTALL_REASON_UNKNOWN;
14655        }
14656
14657        // If the install is being performed by a regular app and the install reason was set to any
14658        // value but enterprise policy, leave the install reason unchanged.
14659        return installReason;
14660    }
14661
14662    void installStage(String packageName, File stagedDir, String stagedCid,
14663            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14664            String installerPackageName, int installerUid, UserHandle user,
14665            Certificate[][] certificates) {
14666        if (DEBUG_EPHEMERAL) {
14667            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14668                Slog.d(TAG, "Ephemeral install of " + packageName);
14669            }
14670        }
14671        final VerificationInfo verificationInfo = new VerificationInfo(
14672                sessionParams.originatingUri, sessionParams.referrerUri,
14673                sessionParams.originatingUid, installerUid);
14674
14675        final OriginInfo origin;
14676        if (stagedDir != null) {
14677            origin = OriginInfo.fromStagedFile(stagedDir);
14678        } else {
14679            origin = OriginInfo.fromStagedContainer(stagedCid);
14680        }
14681
14682        final Message msg = mHandler.obtainMessage(INIT_COPY);
14683        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14684                sessionParams.installReason);
14685        final InstallParams params = new InstallParams(origin, null, observer,
14686                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14687                verificationInfo, user, sessionParams.abiOverride,
14688                sessionParams.grantedRuntimePermissions, certificates, installReason);
14689        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14690        msg.obj = params;
14691
14692        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14693                System.identityHashCode(msg.obj));
14694        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14695                System.identityHashCode(msg.obj));
14696
14697        mHandler.sendMessage(msg);
14698    }
14699
14700    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14701            int userId) {
14702        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14703        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14704                false /*startReceiver*/, pkgSetting.appId, userId);
14705
14706        // Send a session commit broadcast
14707        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14708        info.installReason = pkgSetting.getInstallReason(userId);
14709        info.appPackageName = packageName;
14710        sendSessionCommitBroadcast(info, userId);
14711    }
14712
14713    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14714            boolean includeStopped, int appId, int... userIds) {
14715        if (ArrayUtils.isEmpty(userIds)) {
14716            return;
14717        }
14718        Bundle extras = new Bundle(1);
14719        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14720        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14721
14722        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14723                packageName, extras, 0, null, null, userIds);
14724        if (sendBootCompleted) {
14725            mHandler.post(() -> {
14726                        for (int userId : userIds) {
14727                            sendBootCompletedBroadcastToSystemApp(
14728                                    packageName, includeStopped, userId);
14729                        }
14730                    }
14731            );
14732        }
14733    }
14734
14735    /**
14736     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14737     * automatically without needing an explicit launch.
14738     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14739     */
14740    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14741            int userId) {
14742        // If user is not running, the app didn't miss any broadcast
14743        if (!mUserManagerInternal.isUserRunning(userId)) {
14744            return;
14745        }
14746        final IActivityManager am = ActivityManager.getService();
14747        try {
14748            // Deliver LOCKED_BOOT_COMPLETED first
14749            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14750                    .setPackage(packageName);
14751            if (includeStopped) {
14752                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14753            }
14754            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14755            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14756                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14757
14758            // Deliver BOOT_COMPLETED only if user is unlocked
14759            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14760                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14761                if (includeStopped) {
14762                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14763                }
14764                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14765                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14766            }
14767        } catch (RemoteException e) {
14768            throw e.rethrowFromSystemServer();
14769        }
14770    }
14771
14772    @Override
14773    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14774            int userId) {
14775        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14776        PackageSetting pkgSetting;
14777        final int callingUid = Binder.getCallingUid();
14778        enforceCrossUserPermission(callingUid, userId,
14779                true /* requireFullPermission */, true /* checkShell */,
14780                "setApplicationHiddenSetting for user " + userId);
14781
14782        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14783            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14784            return false;
14785        }
14786
14787        long callingId = Binder.clearCallingIdentity();
14788        try {
14789            boolean sendAdded = false;
14790            boolean sendRemoved = false;
14791            // writer
14792            synchronized (mPackages) {
14793                pkgSetting = mSettings.mPackages.get(packageName);
14794                if (pkgSetting == null) {
14795                    return false;
14796                }
14797                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14798                    return false;
14799                }
14800                // Do not allow "android" is being disabled
14801                if ("android".equals(packageName)) {
14802                    Slog.w(TAG, "Cannot hide package: android");
14803                    return false;
14804                }
14805                // Cannot hide static shared libs as they are considered
14806                // a part of the using app (emulating static linking). Also
14807                // static libs are installed always on internal storage.
14808                PackageParser.Package pkg = mPackages.get(packageName);
14809                if (pkg != null && pkg.staticSharedLibName != null) {
14810                    Slog.w(TAG, "Cannot hide package: " + packageName
14811                            + " providing static shared library: "
14812                            + pkg.staticSharedLibName);
14813                    return false;
14814                }
14815                // Only allow protected packages to hide themselves.
14816                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14817                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14818                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14819                    return false;
14820                }
14821
14822                if (pkgSetting.getHidden(userId) != hidden) {
14823                    pkgSetting.setHidden(hidden, userId);
14824                    mSettings.writePackageRestrictionsLPr(userId);
14825                    if (hidden) {
14826                        sendRemoved = true;
14827                    } else {
14828                        sendAdded = true;
14829                    }
14830                }
14831            }
14832            if (sendAdded) {
14833                sendPackageAddedForUser(packageName, pkgSetting, userId);
14834                return true;
14835            }
14836            if (sendRemoved) {
14837                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14838                        "hiding pkg");
14839                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14840                return true;
14841            }
14842        } finally {
14843            Binder.restoreCallingIdentity(callingId);
14844        }
14845        return false;
14846    }
14847
14848    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14849            int userId) {
14850        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14851        info.removedPackage = packageName;
14852        info.installerPackageName = pkgSetting.installerPackageName;
14853        info.removedUsers = new int[] {userId};
14854        info.broadcastUsers = new int[] {userId};
14855        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14856        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14857    }
14858
14859    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14860        if (pkgList.length > 0) {
14861            Bundle extras = new Bundle(1);
14862            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14863
14864            sendPackageBroadcast(
14865                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14866                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14867                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14868                    new int[] {userId});
14869        }
14870    }
14871
14872    /**
14873     * Returns true if application is not found or there was an error. Otherwise it returns
14874     * the hidden state of the package for the given user.
14875     */
14876    @Override
14877    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14878        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14879        final int callingUid = Binder.getCallingUid();
14880        enforceCrossUserPermission(callingUid, userId,
14881                true /* requireFullPermission */, false /* checkShell */,
14882                "getApplicationHidden for user " + userId);
14883        PackageSetting ps;
14884        long callingId = Binder.clearCallingIdentity();
14885        try {
14886            // writer
14887            synchronized (mPackages) {
14888                ps = mSettings.mPackages.get(packageName);
14889                if (ps == null) {
14890                    return true;
14891                }
14892                if (filterAppAccessLPr(ps, callingUid, userId)) {
14893                    return true;
14894                }
14895                return ps.getHidden(userId);
14896            }
14897        } finally {
14898            Binder.restoreCallingIdentity(callingId);
14899        }
14900    }
14901
14902    /**
14903     * @hide
14904     */
14905    @Override
14906    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14907            int installReason) {
14908        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14909                null);
14910        PackageSetting pkgSetting;
14911        final int callingUid = Binder.getCallingUid();
14912        enforceCrossUserPermission(callingUid, userId,
14913                true /* requireFullPermission */, true /* checkShell */,
14914                "installExistingPackage for user " + userId);
14915        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14916            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14917        }
14918
14919        long callingId = Binder.clearCallingIdentity();
14920        try {
14921            boolean installed = false;
14922            final boolean instantApp =
14923                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14924            final boolean fullApp =
14925                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14926
14927            // writer
14928            synchronized (mPackages) {
14929                pkgSetting = mSettings.mPackages.get(packageName);
14930                if (pkgSetting == null) {
14931                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14932                }
14933                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14934                    // only allow the existing package to be used if it's installed as a full
14935                    // application for at least one user
14936                    boolean installAllowed = false;
14937                    for (int checkUserId : sUserManager.getUserIds()) {
14938                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14939                        if (installAllowed) {
14940                            break;
14941                        }
14942                    }
14943                    if (!installAllowed) {
14944                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14945                    }
14946                }
14947                if (!pkgSetting.getInstalled(userId)) {
14948                    pkgSetting.setInstalled(true, userId);
14949                    pkgSetting.setHidden(false, userId);
14950                    pkgSetting.setInstallReason(installReason, userId);
14951                    mSettings.writePackageRestrictionsLPr(userId);
14952                    mSettings.writeKernelMappingLPr(pkgSetting);
14953                    installed = true;
14954                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14955                    // upgrade app from instant to full; we don't allow app downgrade
14956                    installed = true;
14957                }
14958                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14959            }
14960
14961            if (installed) {
14962                if (pkgSetting.pkg != null) {
14963                    synchronized (mInstallLock) {
14964                        // We don't need to freeze for a brand new install
14965                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14966                    }
14967                }
14968                sendPackageAddedForUser(packageName, pkgSetting, userId);
14969                synchronized (mPackages) {
14970                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14971                }
14972            }
14973        } finally {
14974            Binder.restoreCallingIdentity(callingId);
14975        }
14976
14977        return PackageManager.INSTALL_SUCCEEDED;
14978    }
14979
14980    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14981            boolean instantApp, boolean fullApp) {
14982        // no state specified; do nothing
14983        if (!instantApp && !fullApp) {
14984            return;
14985        }
14986        if (userId != UserHandle.USER_ALL) {
14987            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14988                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14989            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14990                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14991            }
14992        } else {
14993            for (int currentUserId : sUserManager.getUserIds()) {
14994                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14995                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14996                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14997                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14998                }
14999            }
15000        }
15001    }
15002
15003    boolean isUserRestricted(int userId, String restrictionKey) {
15004        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15005        if (restrictions.getBoolean(restrictionKey, false)) {
15006            Log.w(TAG, "User is restricted: " + restrictionKey);
15007            return true;
15008        }
15009        return false;
15010    }
15011
15012    @Override
15013    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15014            int userId) {
15015        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15016        final int callingUid = Binder.getCallingUid();
15017        enforceCrossUserPermission(callingUid, userId,
15018                true /* requireFullPermission */, true /* checkShell */,
15019                "setPackagesSuspended for user " + userId);
15020
15021        if (ArrayUtils.isEmpty(packageNames)) {
15022            return packageNames;
15023        }
15024
15025        // List of package names for whom the suspended state has changed.
15026        List<String> changedPackages = new ArrayList<>(packageNames.length);
15027        // List of package names for whom the suspended state is not set as requested in this
15028        // method.
15029        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15030        long callingId = Binder.clearCallingIdentity();
15031        try {
15032            for (int i = 0; i < packageNames.length; i++) {
15033                String packageName = packageNames[i];
15034                boolean changed = false;
15035                final int appId;
15036                synchronized (mPackages) {
15037                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15038                    if (pkgSetting == null
15039                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15040                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15041                                + "\". Skipping suspending/un-suspending.");
15042                        unactionedPackages.add(packageName);
15043                        continue;
15044                    }
15045                    appId = pkgSetting.appId;
15046                    if (pkgSetting.getSuspended(userId) != suspended) {
15047                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15048                            unactionedPackages.add(packageName);
15049                            continue;
15050                        }
15051                        pkgSetting.setSuspended(suspended, userId);
15052                        mSettings.writePackageRestrictionsLPr(userId);
15053                        changed = true;
15054                        changedPackages.add(packageName);
15055                    }
15056                }
15057
15058                if (changed && suspended) {
15059                    killApplication(packageName, UserHandle.getUid(userId, appId),
15060                            "suspending package");
15061                }
15062            }
15063        } finally {
15064            Binder.restoreCallingIdentity(callingId);
15065        }
15066
15067        if (!changedPackages.isEmpty()) {
15068            sendPackagesSuspendedForUser(changedPackages.toArray(
15069                    new String[changedPackages.size()]), userId, suspended);
15070        }
15071
15072        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15073    }
15074
15075    @Override
15076    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15077        final int callingUid = Binder.getCallingUid();
15078        enforceCrossUserPermission(callingUid, userId,
15079                true /* requireFullPermission */, false /* checkShell */,
15080                "isPackageSuspendedForUser for user " + userId);
15081        synchronized (mPackages) {
15082            final PackageSetting ps = mSettings.mPackages.get(packageName);
15083            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15084                throw new IllegalArgumentException("Unknown target package: " + packageName);
15085            }
15086            return ps.getSuspended(userId);
15087        }
15088    }
15089
15090    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15091        if (isPackageDeviceAdmin(packageName, userId)) {
15092            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15093                    + "\": has an active device admin");
15094            return false;
15095        }
15096
15097        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15098        if (packageName.equals(activeLauncherPackageName)) {
15099            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15100                    + "\": contains the active launcher");
15101            return false;
15102        }
15103
15104        if (packageName.equals(mRequiredInstallerPackage)) {
15105            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15106                    + "\": required for package installation");
15107            return false;
15108        }
15109
15110        if (packageName.equals(mRequiredUninstallerPackage)) {
15111            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15112                    + "\": required for package uninstallation");
15113            return false;
15114        }
15115
15116        if (packageName.equals(mRequiredVerifierPackage)) {
15117            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15118                    + "\": required for package verification");
15119            return false;
15120        }
15121
15122        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15123            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15124                    + "\": is the default dialer");
15125            return false;
15126        }
15127
15128        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15129            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15130                    + "\": protected package");
15131            return false;
15132        }
15133
15134        // Cannot suspend static shared libs as they are considered
15135        // a part of the using app (emulating static linking). Also
15136        // static libs are installed always on internal storage.
15137        PackageParser.Package pkg = mPackages.get(packageName);
15138        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15139            Slog.w(TAG, "Cannot suspend package: " + packageName
15140                    + " providing static shared library: "
15141                    + pkg.staticSharedLibName);
15142            return false;
15143        }
15144
15145        return true;
15146    }
15147
15148    private String getActiveLauncherPackageName(int userId) {
15149        Intent intent = new Intent(Intent.ACTION_MAIN);
15150        intent.addCategory(Intent.CATEGORY_HOME);
15151        ResolveInfo resolveInfo = resolveIntent(
15152                intent,
15153                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15154                PackageManager.MATCH_DEFAULT_ONLY,
15155                userId);
15156
15157        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15158    }
15159
15160    private String getDefaultDialerPackageName(int userId) {
15161        synchronized (mPackages) {
15162            return mSettings.getDefaultDialerPackageNameLPw(userId);
15163        }
15164    }
15165
15166    @Override
15167    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15168        mContext.enforceCallingOrSelfPermission(
15169                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15170                "Only package verification agents can verify applications");
15171
15172        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15173        final PackageVerificationResponse response = new PackageVerificationResponse(
15174                verificationCode, Binder.getCallingUid());
15175        msg.arg1 = id;
15176        msg.obj = response;
15177        mHandler.sendMessage(msg);
15178    }
15179
15180    @Override
15181    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15182            long millisecondsToDelay) {
15183        mContext.enforceCallingOrSelfPermission(
15184                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15185                "Only package verification agents can extend verification timeouts");
15186
15187        final PackageVerificationState state = mPendingVerification.get(id);
15188        final PackageVerificationResponse response = new PackageVerificationResponse(
15189                verificationCodeAtTimeout, Binder.getCallingUid());
15190
15191        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15192            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15193        }
15194        if (millisecondsToDelay < 0) {
15195            millisecondsToDelay = 0;
15196        }
15197        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15198                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15199            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15200        }
15201
15202        if ((state != null) && !state.timeoutExtended()) {
15203            state.extendTimeout();
15204
15205            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15206            msg.arg1 = id;
15207            msg.obj = response;
15208            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15209        }
15210    }
15211
15212    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15213            int verificationCode, UserHandle user) {
15214        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15215        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15216        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15217        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15218        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15219
15220        mContext.sendBroadcastAsUser(intent, user,
15221                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15222    }
15223
15224    private ComponentName matchComponentForVerifier(String packageName,
15225            List<ResolveInfo> receivers) {
15226        ActivityInfo targetReceiver = null;
15227
15228        final int NR = receivers.size();
15229        for (int i = 0; i < NR; i++) {
15230            final ResolveInfo info = receivers.get(i);
15231            if (info.activityInfo == null) {
15232                continue;
15233            }
15234
15235            if (packageName.equals(info.activityInfo.packageName)) {
15236                targetReceiver = info.activityInfo;
15237                break;
15238            }
15239        }
15240
15241        if (targetReceiver == null) {
15242            return null;
15243        }
15244
15245        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15246    }
15247
15248    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15249            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15250        if (pkgInfo.verifiers.length == 0) {
15251            return null;
15252        }
15253
15254        final int N = pkgInfo.verifiers.length;
15255        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15256        for (int i = 0; i < N; i++) {
15257            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15258
15259            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15260                    receivers);
15261            if (comp == null) {
15262                continue;
15263            }
15264
15265            final int verifierUid = getUidForVerifier(verifierInfo);
15266            if (verifierUid == -1) {
15267                continue;
15268            }
15269
15270            if (DEBUG_VERIFY) {
15271                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15272                        + " with the correct signature");
15273            }
15274            sufficientVerifiers.add(comp);
15275            verificationState.addSufficientVerifier(verifierUid);
15276        }
15277
15278        return sufficientVerifiers;
15279    }
15280
15281    private int getUidForVerifier(VerifierInfo verifierInfo) {
15282        synchronized (mPackages) {
15283            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15284            if (pkg == null) {
15285                return -1;
15286            } else if (pkg.mSignatures.length != 1) {
15287                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15288                        + " has more than one signature; ignoring");
15289                return -1;
15290            }
15291
15292            /*
15293             * If the public key of the package's signature does not match
15294             * our expected public key, then this is a different package and
15295             * we should skip.
15296             */
15297
15298            final byte[] expectedPublicKey;
15299            try {
15300                final Signature verifierSig = pkg.mSignatures[0];
15301                final PublicKey publicKey = verifierSig.getPublicKey();
15302                expectedPublicKey = publicKey.getEncoded();
15303            } catch (CertificateException e) {
15304                return -1;
15305            }
15306
15307            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15308
15309            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15310                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15311                        + " does not have the expected public key; ignoring");
15312                return -1;
15313            }
15314
15315            return pkg.applicationInfo.uid;
15316        }
15317    }
15318
15319    @Override
15320    public void finishPackageInstall(int token, boolean didLaunch) {
15321        enforceSystemOrRoot("Only the system is allowed to finish installs");
15322
15323        if (DEBUG_INSTALL) {
15324            Slog.v(TAG, "BM finishing package install for " + token);
15325        }
15326        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15327
15328        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15329        mHandler.sendMessage(msg);
15330    }
15331
15332    /**
15333     * Get the verification agent timeout.  Used for both the APK verifier and the
15334     * intent filter verifier.
15335     *
15336     * @return verification timeout in milliseconds
15337     */
15338    private long getVerificationTimeout() {
15339        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15340                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15341                DEFAULT_VERIFICATION_TIMEOUT);
15342    }
15343
15344    /**
15345     * Get the default verification agent response code.
15346     *
15347     * @return default verification response code
15348     */
15349    private int getDefaultVerificationResponse(UserHandle user) {
15350        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15351            return PackageManager.VERIFICATION_REJECT;
15352        }
15353        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15354                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15355                DEFAULT_VERIFICATION_RESPONSE);
15356    }
15357
15358    /**
15359     * Check whether or not package verification has been enabled.
15360     *
15361     * @return true if verification should be performed
15362     */
15363    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15364        if (!DEFAULT_VERIFY_ENABLE) {
15365            return false;
15366        }
15367
15368        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15369
15370        // Check if installing from ADB
15371        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15372            // Do not run verification in a test harness environment
15373            if (ActivityManager.isRunningInTestHarness()) {
15374                return false;
15375            }
15376            if (ensureVerifyAppsEnabled) {
15377                return true;
15378            }
15379            // Check if the developer does not want package verification for ADB installs
15380            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15381                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15382                return false;
15383            }
15384        } else {
15385            // only when not installed from ADB, skip verification for instant apps when
15386            // the installer and verifier are the same.
15387            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15388                if (mInstantAppInstallerActivity != null
15389                        && mInstantAppInstallerActivity.packageName.equals(
15390                                mRequiredVerifierPackage)) {
15391                    try {
15392                        mContext.getSystemService(AppOpsManager.class)
15393                                .checkPackage(installerUid, mRequiredVerifierPackage);
15394                        if (DEBUG_VERIFY) {
15395                            Slog.i(TAG, "disable verification for instant app");
15396                        }
15397                        return false;
15398                    } catch (SecurityException ignore) { }
15399                }
15400            }
15401        }
15402
15403        if (ensureVerifyAppsEnabled) {
15404            return true;
15405        }
15406
15407        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15408                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15409    }
15410
15411    @Override
15412    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15413            throws RemoteException {
15414        mContext.enforceCallingOrSelfPermission(
15415                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15416                "Only intentfilter verification agents can verify applications");
15417
15418        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15419        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15420                Binder.getCallingUid(), verificationCode, failedDomains);
15421        msg.arg1 = id;
15422        msg.obj = response;
15423        mHandler.sendMessage(msg);
15424    }
15425
15426    @Override
15427    public int getIntentVerificationStatus(String packageName, int userId) {
15428        final int callingUid = Binder.getCallingUid();
15429        if (UserHandle.getUserId(callingUid) != userId) {
15430            mContext.enforceCallingOrSelfPermission(
15431                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15432                    "getIntentVerificationStatus" + userId);
15433        }
15434        if (getInstantAppPackageName(callingUid) != null) {
15435            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15436        }
15437        synchronized (mPackages) {
15438            final PackageSetting ps = mSettings.mPackages.get(packageName);
15439            if (ps == null
15440                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15441                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15442            }
15443            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15444        }
15445    }
15446
15447    @Override
15448    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15449        mContext.enforceCallingOrSelfPermission(
15450                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15451
15452        boolean result = false;
15453        synchronized (mPackages) {
15454            final PackageSetting ps = mSettings.mPackages.get(packageName);
15455            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15456                return false;
15457            }
15458            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15459        }
15460        if (result) {
15461            scheduleWritePackageRestrictionsLocked(userId);
15462        }
15463        return result;
15464    }
15465
15466    @Override
15467    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15468            String packageName) {
15469        final int callingUid = Binder.getCallingUid();
15470        if (getInstantAppPackageName(callingUid) != null) {
15471            return ParceledListSlice.emptyList();
15472        }
15473        synchronized (mPackages) {
15474            final PackageSetting ps = mSettings.mPackages.get(packageName);
15475            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15476                return ParceledListSlice.emptyList();
15477            }
15478            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15479        }
15480    }
15481
15482    @Override
15483    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15484        if (TextUtils.isEmpty(packageName)) {
15485            return ParceledListSlice.emptyList();
15486        }
15487        final int callingUid = Binder.getCallingUid();
15488        final int callingUserId = UserHandle.getUserId(callingUid);
15489        synchronized (mPackages) {
15490            PackageParser.Package pkg = mPackages.get(packageName);
15491            if (pkg == null || pkg.activities == null) {
15492                return ParceledListSlice.emptyList();
15493            }
15494            if (pkg.mExtras == null) {
15495                return ParceledListSlice.emptyList();
15496            }
15497            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15498            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15499                return ParceledListSlice.emptyList();
15500            }
15501            final int count = pkg.activities.size();
15502            ArrayList<IntentFilter> result = new ArrayList<>();
15503            for (int n=0; n<count; n++) {
15504                PackageParser.Activity activity = pkg.activities.get(n);
15505                if (activity.intents != null && activity.intents.size() > 0) {
15506                    result.addAll(activity.intents);
15507                }
15508            }
15509            return new ParceledListSlice<>(result);
15510        }
15511    }
15512
15513    @Override
15514    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15515        mContext.enforceCallingOrSelfPermission(
15516                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15517        if (UserHandle.getCallingUserId() != userId) {
15518            mContext.enforceCallingOrSelfPermission(
15519                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15520        }
15521
15522        synchronized (mPackages) {
15523            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15524            if (packageName != null) {
15525                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
15526                        packageName, userId);
15527            }
15528            return result;
15529        }
15530    }
15531
15532    @Override
15533    public String getDefaultBrowserPackageName(int userId) {
15534        if (UserHandle.getCallingUserId() != userId) {
15535            mContext.enforceCallingOrSelfPermission(
15536                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15537        }
15538        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15539            return null;
15540        }
15541        synchronized (mPackages) {
15542            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15543        }
15544    }
15545
15546    /**
15547     * Get the "allow unknown sources" setting.
15548     *
15549     * @return the current "allow unknown sources" setting
15550     */
15551    private int getUnknownSourcesSettings() {
15552        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15553                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15554                -1);
15555    }
15556
15557    @Override
15558    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15559        final int callingUid = Binder.getCallingUid();
15560        if (getInstantAppPackageName(callingUid) != null) {
15561            return;
15562        }
15563        // writer
15564        synchronized (mPackages) {
15565            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15566            if (targetPackageSetting == null
15567                    || filterAppAccessLPr(
15568                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15569                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15570            }
15571
15572            PackageSetting installerPackageSetting;
15573            if (installerPackageName != null) {
15574                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15575                if (installerPackageSetting == null) {
15576                    throw new IllegalArgumentException("Unknown installer package: "
15577                            + installerPackageName);
15578                }
15579            } else {
15580                installerPackageSetting = null;
15581            }
15582
15583            Signature[] callerSignature;
15584            Object obj = mSettings.getUserIdLPr(callingUid);
15585            if (obj != null) {
15586                if (obj instanceof SharedUserSetting) {
15587                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15588                } else if (obj instanceof PackageSetting) {
15589                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15590                } else {
15591                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15592                }
15593            } else {
15594                throw new SecurityException("Unknown calling UID: " + callingUid);
15595            }
15596
15597            // Verify: can't set installerPackageName to a package that is
15598            // not signed with the same cert as the caller.
15599            if (installerPackageSetting != null) {
15600                if (compareSignatures(callerSignature,
15601                        installerPackageSetting.signatures.mSignatures)
15602                        != PackageManager.SIGNATURE_MATCH) {
15603                    throw new SecurityException(
15604                            "Caller does not have same cert as new installer package "
15605                            + installerPackageName);
15606                }
15607            }
15608
15609            // Verify: if target already has an installer package, it must
15610            // be signed with the same cert as the caller.
15611            if (targetPackageSetting.installerPackageName != null) {
15612                PackageSetting setting = mSettings.mPackages.get(
15613                        targetPackageSetting.installerPackageName);
15614                // If the currently set package isn't valid, then it's always
15615                // okay to change it.
15616                if (setting != null) {
15617                    if (compareSignatures(callerSignature,
15618                            setting.signatures.mSignatures)
15619                            != PackageManager.SIGNATURE_MATCH) {
15620                        throw new SecurityException(
15621                                "Caller does not have same cert as old installer package "
15622                                + targetPackageSetting.installerPackageName);
15623                    }
15624                }
15625            }
15626
15627            // Okay!
15628            targetPackageSetting.installerPackageName = installerPackageName;
15629            if (installerPackageName != null) {
15630                mSettings.mInstallerPackages.add(installerPackageName);
15631            }
15632            scheduleWriteSettingsLocked();
15633        }
15634    }
15635
15636    @Override
15637    public void setApplicationCategoryHint(String packageName, int categoryHint,
15638            String callerPackageName) {
15639        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15640            throw new SecurityException("Instant applications don't have access to this method");
15641        }
15642        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15643                callerPackageName);
15644        synchronized (mPackages) {
15645            PackageSetting ps = mSettings.mPackages.get(packageName);
15646            if (ps == null) {
15647                throw new IllegalArgumentException("Unknown target package " + packageName);
15648            }
15649            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15650                throw new IllegalArgumentException("Unknown target package " + packageName);
15651            }
15652            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15653                throw new IllegalArgumentException("Calling package " + callerPackageName
15654                        + " is not installer for " + packageName);
15655            }
15656
15657            if (ps.categoryHint != categoryHint) {
15658                ps.categoryHint = categoryHint;
15659                scheduleWriteSettingsLocked();
15660            }
15661        }
15662    }
15663
15664    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15665        // Queue up an async operation since the package installation may take a little while.
15666        mHandler.post(new Runnable() {
15667            public void run() {
15668                mHandler.removeCallbacks(this);
15669                 // Result object to be returned
15670                PackageInstalledInfo res = new PackageInstalledInfo();
15671                res.setReturnCode(currentStatus);
15672                res.uid = -1;
15673                res.pkg = null;
15674                res.removedInfo = null;
15675                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15676                    args.doPreInstall(res.returnCode);
15677                    synchronized (mInstallLock) {
15678                        installPackageTracedLI(args, res);
15679                    }
15680                    args.doPostInstall(res.returnCode, res.uid);
15681                }
15682
15683                // A restore should be performed at this point if (a) the install
15684                // succeeded, (b) the operation is not an update, and (c) the new
15685                // package has not opted out of backup participation.
15686                final boolean update = res.removedInfo != null
15687                        && res.removedInfo.removedPackage != null;
15688                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15689                boolean doRestore = !update
15690                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15691
15692                // Set up the post-install work request bookkeeping.  This will be used
15693                // and cleaned up by the post-install event handling regardless of whether
15694                // there's a restore pass performed.  Token values are >= 1.
15695                int token;
15696                if (mNextInstallToken < 0) mNextInstallToken = 1;
15697                token = mNextInstallToken++;
15698
15699                PostInstallData data = new PostInstallData(args, res);
15700                mRunningInstalls.put(token, data);
15701                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15702
15703                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15704                    // Pass responsibility to the Backup Manager.  It will perform a
15705                    // restore if appropriate, then pass responsibility back to the
15706                    // Package Manager to run the post-install observer callbacks
15707                    // and broadcasts.
15708                    IBackupManager bm = IBackupManager.Stub.asInterface(
15709                            ServiceManager.getService(Context.BACKUP_SERVICE));
15710                    if (bm != null) {
15711                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15712                                + " to BM for possible restore");
15713                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15714                        try {
15715                            // TODO: http://b/22388012
15716                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15717                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15718                            } else {
15719                                doRestore = false;
15720                            }
15721                        } catch (RemoteException e) {
15722                            // can't happen; the backup manager is local
15723                        } catch (Exception e) {
15724                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15725                            doRestore = false;
15726                        }
15727                    } else {
15728                        Slog.e(TAG, "Backup Manager not found!");
15729                        doRestore = false;
15730                    }
15731                }
15732
15733                if (!doRestore) {
15734                    // No restore possible, or the Backup Manager was mysteriously not
15735                    // available -- just fire the post-install work request directly.
15736                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15737
15738                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15739
15740                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15741                    mHandler.sendMessage(msg);
15742                }
15743            }
15744        });
15745    }
15746
15747    /**
15748     * Callback from PackageSettings whenever an app is first transitioned out of the
15749     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15750     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15751     * here whether the app is the target of an ongoing install, and only send the
15752     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15753     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15754     * handling.
15755     */
15756    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15757        // Serialize this with the rest of the install-process message chain.  In the
15758        // restore-at-install case, this Runnable will necessarily run before the
15759        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15760        // are coherent.  In the non-restore case, the app has already completed install
15761        // and been launched through some other means, so it is not in a problematic
15762        // state for observers to see the FIRST_LAUNCH signal.
15763        mHandler.post(new Runnable() {
15764            @Override
15765            public void run() {
15766                for (int i = 0; i < mRunningInstalls.size(); i++) {
15767                    final PostInstallData data = mRunningInstalls.valueAt(i);
15768                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15769                        continue;
15770                    }
15771                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15772                        // right package; but is it for the right user?
15773                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15774                            if (userId == data.res.newUsers[uIndex]) {
15775                                if (DEBUG_BACKUP) {
15776                                    Slog.i(TAG, "Package " + pkgName
15777                                            + " being restored so deferring FIRST_LAUNCH");
15778                                }
15779                                return;
15780                            }
15781                        }
15782                    }
15783                }
15784                // didn't find it, so not being restored
15785                if (DEBUG_BACKUP) {
15786                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15787                }
15788                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15789            }
15790        });
15791    }
15792
15793    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15794        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15795                installerPkg, null, userIds);
15796    }
15797
15798    private abstract class HandlerParams {
15799        private static final int MAX_RETRIES = 4;
15800
15801        /**
15802         * Number of times startCopy() has been attempted and had a non-fatal
15803         * error.
15804         */
15805        private int mRetries = 0;
15806
15807        /** User handle for the user requesting the information or installation. */
15808        private final UserHandle mUser;
15809        String traceMethod;
15810        int traceCookie;
15811
15812        HandlerParams(UserHandle user) {
15813            mUser = user;
15814        }
15815
15816        UserHandle getUser() {
15817            return mUser;
15818        }
15819
15820        HandlerParams setTraceMethod(String traceMethod) {
15821            this.traceMethod = traceMethod;
15822            return this;
15823        }
15824
15825        HandlerParams setTraceCookie(int traceCookie) {
15826            this.traceCookie = traceCookie;
15827            return this;
15828        }
15829
15830        final boolean startCopy() {
15831            boolean res;
15832            try {
15833                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15834
15835                if (++mRetries > MAX_RETRIES) {
15836                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15837                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15838                    handleServiceError();
15839                    return false;
15840                } else {
15841                    handleStartCopy();
15842                    res = true;
15843                }
15844            } catch (RemoteException e) {
15845                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15846                mHandler.sendEmptyMessage(MCS_RECONNECT);
15847                res = false;
15848            }
15849            handleReturnCode();
15850            return res;
15851        }
15852
15853        final void serviceError() {
15854            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15855            handleServiceError();
15856            handleReturnCode();
15857        }
15858
15859        abstract void handleStartCopy() throws RemoteException;
15860        abstract void handleServiceError();
15861        abstract void handleReturnCode();
15862    }
15863
15864    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15865        for (File path : paths) {
15866            try {
15867                mcs.clearDirectory(path.getAbsolutePath());
15868            } catch (RemoteException e) {
15869            }
15870        }
15871    }
15872
15873    static class OriginInfo {
15874        /**
15875         * Location where install is coming from, before it has been
15876         * copied/renamed into place. This could be a single monolithic APK
15877         * file, or a cluster directory. This location may be untrusted.
15878         */
15879        final File file;
15880        final String cid;
15881
15882        /**
15883         * Flag indicating that {@link #file} or {@link #cid} has already been
15884         * staged, meaning downstream users don't need to defensively copy the
15885         * contents.
15886         */
15887        final boolean staged;
15888
15889        /**
15890         * Flag indicating that {@link #file} or {@link #cid} is an already
15891         * installed app that is being moved.
15892         */
15893        final boolean existing;
15894
15895        final String resolvedPath;
15896        final File resolvedFile;
15897
15898        static OriginInfo fromNothing() {
15899            return new OriginInfo(null, null, false, false);
15900        }
15901
15902        static OriginInfo fromUntrustedFile(File file) {
15903            return new OriginInfo(file, null, false, false);
15904        }
15905
15906        static OriginInfo fromExistingFile(File file) {
15907            return new OriginInfo(file, null, false, true);
15908        }
15909
15910        static OriginInfo fromStagedFile(File file) {
15911            return new OriginInfo(file, null, true, false);
15912        }
15913
15914        static OriginInfo fromStagedContainer(String cid) {
15915            return new OriginInfo(null, cid, true, false);
15916        }
15917
15918        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15919            this.file = file;
15920            this.cid = cid;
15921            this.staged = staged;
15922            this.existing = existing;
15923
15924            if (cid != null) {
15925                resolvedPath = PackageHelper.getSdDir(cid);
15926                resolvedFile = new File(resolvedPath);
15927            } else if (file != null) {
15928                resolvedPath = file.getAbsolutePath();
15929                resolvedFile = file;
15930            } else {
15931                resolvedPath = null;
15932                resolvedFile = null;
15933            }
15934        }
15935    }
15936
15937    static class MoveInfo {
15938        final int moveId;
15939        final String fromUuid;
15940        final String toUuid;
15941        final String packageName;
15942        final String dataAppName;
15943        final int appId;
15944        final String seinfo;
15945        final int targetSdkVersion;
15946
15947        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15948                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15949            this.moveId = moveId;
15950            this.fromUuid = fromUuid;
15951            this.toUuid = toUuid;
15952            this.packageName = packageName;
15953            this.dataAppName = dataAppName;
15954            this.appId = appId;
15955            this.seinfo = seinfo;
15956            this.targetSdkVersion = targetSdkVersion;
15957        }
15958    }
15959
15960    static class VerificationInfo {
15961        /** A constant used to indicate that a uid value is not present. */
15962        public static final int NO_UID = -1;
15963
15964        /** URI referencing where the package was downloaded from. */
15965        final Uri originatingUri;
15966
15967        /** HTTP referrer URI associated with the originatingURI. */
15968        final Uri referrer;
15969
15970        /** UID of the application that the install request originated from. */
15971        final int originatingUid;
15972
15973        /** UID of application requesting the install */
15974        final int installerUid;
15975
15976        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15977            this.originatingUri = originatingUri;
15978            this.referrer = referrer;
15979            this.originatingUid = originatingUid;
15980            this.installerUid = installerUid;
15981        }
15982    }
15983
15984    class InstallParams extends HandlerParams {
15985        final OriginInfo origin;
15986        final MoveInfo move;
15987        final IPackageInstallObserver2 observer;
15988        int installFlags;
15989        final String installerPackageName;
15990        final String volumeUuid;
15991        private InstallArgs mArgs;
15992        private int mRet;
15993        final String packageAbiOverride;
15994        final String[] grantedRuntimePermissions;
15995        final VerificationInfo verificationInfo;
15996        final Certificate[][] certificates;
15997        final int installReason;
15998
15999        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16000                int installFlags, String installerPackageName, String volumeUuid,
16001                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16002                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16003            super(user);
16004            this.origin = origin;
16005            this.move = move;
16006            this.observer = observer;
16007            this.installFlags = installFlags;
16008            this.installerPackageName = installerPackageName;
16009            this.volumeUuid = volumeUuid;
16010            this.verificationInfo = verificationInfo;
16011            this.packageAbiOverride = packageAbiOverride;
16012            this.grantedRuntimePermissions = grantedPermissions;
16013            this.certificates = certificates;
16014            this.installReason = installReason;
16015        }
16016
16017        @Override
16018        public String toString() {
16019            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16020                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16021        }
16022
16023        private int installLocationPolicy(PackageInfoLite pkgLite) {
16024            String packageName = pkgLite.packageName;
16025            int installLocation = pkgLite.installLocation;
16026            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16027            // reader
16028            synchronized (mPackages) {
16029                // Currently installed package which the new package is attempting to replace or
16030                // null if no such package is installed.
16031                PackageParser.Package installedPkg = mPackages.get(packageName);
16032                // Package which currently owns the data which the new package will own if installed.
16033                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16034                // will be null whereas dataOwnerPkg will contain information about the package
16035                // which was uninstalled while keeping its data.
16036                PackageParser.Package dataOwnerPkg = installedPkg;
16037                if (dataOwnerPkg  == null) {
16038                    PackageSetting ps = mSettings.mPackages.get(packageName);
16039                    if (ps != null) {
16040                        dataOwnerPkg = ps.pkg;
16041                    }
16042                }
16043
16044                if (dataOwnerPkg != null) {
16045                    // If installed, the package will get access to data left on the device by its
16046                    // predecessor. As a security measure, this is permited only if this is not a
16047                    // version downgrade or if the predecessor package is marked as debuggable and
16048                    // a downgrade is explicitly requested.
16049                    //
16050                    // On debuggable platform builds, downgrades are permitted even for
16051                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16052                    // not offer security guarantees and thus it's OK to disable some security
16053                    // mechanisms to make debugging/testing easier on those builds. However, even on
16054                    // debuggable builds downgrades of packages are permitted only if requested via
16055                    // installFlags. This is because we aim to keep the behavior of debuggable
16056                    // platform builds as close as possible to the behavior of non-debuggable
16057                    // platform builds.
16058                    final boolean downgradeRequested =
16059                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16060                    final boolean packageDebuggable =
16061                                (dataOwnerPkg.applicationInfo.flags
16062                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16063                    final boolean downgradePermitted =
16064                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16065                    if (!downgradePermitted) {
16066                        try {
16067                            checkDowngrade(dataOwnerPkg, pkgLite);
16068                        } catch (PackageManagerException e) {
16069                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16070                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16071                        }
16072                    }
16073                }
16074
16075                if (installedPkg != null) {
16076                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16077                        // Check for updated system application.
16078                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16079                            if (onSd) {
16080                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16081                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16082                            }
16083                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16084                        } else {
16085                            if (onSd) {
16086                                // Install flag overrides everything.
16087                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16088                            }
16089                            // If current upgrade specifies particular preference
16090                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16091                                // Application explicitly specified internal.
16092                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16093                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16094                                // App explictly prefers external. Let policy decide
16095                            } else {
16096                                // Prefer previous location
16097                                if (isExternal(installedPkg)) {
16098                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16099                                }
16100                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16101                            }
16102                        }
16103                    } else {
16104                        // Invalid install. Return error code
16105                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16106                    }
16107                }
16108            }
16109            // All the special cases have been taken care of.
16110            // Return result based on recommended install location.
16111            if (onSd) {
16112                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16113            }
16114            return pkgLite.recommendedInstallLocation;
16115        }
16116
16117        /*
16118         * Invoke remote method to get package information and install
16119         * location values. Override install location based on default
16120         * policy if needed and then create install arguments based
16121         * on the install location.
16122         */
16123        public void handleStartCopy() throws RemoteException {
16124            int ret = PackageManager.INSTALL_SUCCEEDED;
16125
16126            // If we're already staged, we've firmly committed to an install location
16127            if (origin.staged) {
16128                if (origin.file != null) {
16129                    installFlags |= PackageManager.INSTALL_INTERNAL;
16130                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16131                } else if (origin.cid != null) {
16132                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16133                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16134                } else {
16135                    throw new IllegalStateException("Invalid stage location");
16136                }
16137            }
16138
16139            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16140            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16141            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16142            PackageInfoLite pkgLite = null;
16143
16144            if (onInt && onSd) {
16145                // Check if both bits are set.
16146                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16147                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16148            } else if (onSd && ephemeral) {
16149                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16150                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16151            } else {
16152                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16153                        packageAbiOverride);
16154
16155                if (DEBUG_EPHEMERAL && ephemeral) {
16156                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16157                }
16158
16159                /*
16160                 * If we have too little free space, try to free cache
16161                 * before giving up.
16162                 */
16163                if (!origin.staged && pkgLite.recommendedInstallLocation
16164                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16165                    // TODO: focus freeing disk space on the target device
16166                    final StorageManager storage = StorageManager.from(mContext);
16167                    final long lowThreshold = storage.getStorageLowBytes(
16168                            Environment.getDataDirectory());
16169
16170                    final long sizeBytes = mContainerService.calculateInstalledSize(
16171                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16172
16173                    try {
16174                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16175                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16176                                installFlags, packageAbiOverride);
16177                    } catch (InstallerException e) {
16178                        Slog.w(TAG, "Failed to free cache", e);
16179                    }
16180
16181                    /*
16182                     * The cache free must have deleted the file we
16183                     * downloaded to install.
16184                     *
16185                     * TODO: fix the "freeCache" call to not delete
16186                     *       the file we care about.
16187                     */
16188                    if (pkgLite.recommendedInstallLocation
16189                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16190                        pkgLite.recommendedInstallLocation
16191                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16192                    }
16193                }
16194            }
16195
16196            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16197                int loc = pkgLite.recommendedInstallLocation;
16198                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16199                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16200                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16201                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16202                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16203                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16204                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16205                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16206                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16207                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16208                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16209                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16210                } else {
16211                    // Override with defaults if needed.
16212                    loc = installLocationPolicy(pkgLite);
16213                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16214                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16215                    } else if (!onSd && !onInt) {
16216                        // Override install location with flags
16217                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16218                            // Set the flag to install on external media.
16219                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16220                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16221                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16222                            if (DEBUG_EPHEMERAL) {
16223                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16224                            }
16225                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16226                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16227                                    |PackageManager.INSTALL_INTERNAL);
16228                        } else {
16229                            // Make sure the flag for installing on external
16230                            // media is unset
16231                            installFlags |= PackageManager.INSTALL_INTERNAL;
16232                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16233                        }
16234                    }
16235                }
16236            }
16237
16238            final InstallArgs args = createInstallArgs(this);
16239            mArgs = args;
16240
16241            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16242                // TODO: http://b/22976637
16243                // Apps installed for "all" users use the device owner to verify the app
16244                UserHandle verifierUser = getUser();
16245                if (verifierUser == UserHandle.ALL) {
16246                    verifierUser = UserHandle.SYSTEM;
16247                }
16248
16249                /*
16250                 * Determine if we have any installed package verifiers. If we
16251                 * do, then we'll defer to them to verify the packages.
16252                 */
16253                final int requiredUid = mRequiredVerifierPackage == null ? -1
16254                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16255                                verifierUser.getIdentifier());
16256                final int installerUid =
16257                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16258                if (!origin.existing && requiredUid != -1
16259                        && isVerificationEnabled(
16260                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16261                    final Intent verification = new Intent(
16262                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16263                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16264                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16265                            PACKAGE_MIME_TYPE);
16266                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16267
16268                    // Query all live verifiers based on current user state
16269                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16270                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16271                            false /*allowDynamicSplits*/);
16272
16273                    if (DEBUG_VERIFY) {
16274                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16275                                + verification.toString() + " with " + pkgLite.verifiers.length
16276                                + " optional verifiers");
16277                    }
16278
16279                    final int verificationId = mPendingVerificationToken++;
16280
16281                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16282
16283                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16284                            installerPackageName);
16285
16286                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16287                            installFlags);
16288
16289                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16290                            pkgLite.packageName);
16291
16292                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16293                            pkgLite.versionCode);
16294
16295                    if (verificationInfo != null) {
16296                        if (verificationInfo.originatingUri != null) {
16297                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16298                                    verificationInfo.originatingUri);
16299                        }
16300                        if (verificationInfo.referrer != null) {
16301                            verification.putExtra(Intent.EXTRA_REFERRER,
16302                                    verificationInfo.referrer);
16303                        }
16304                        if (verificationInfo.originatingUid >= 0) {
16305                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16306                                    verificationInfo.originatingUid);
16307                        }
16308                        if (verificationInfo.installerUid >= 0) {
16309                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16310                                    verificationInfo.installerUid);
16311                        }
16312                    }
16313
16314                    final PackageVerificationState verificationState = new PackageVerificationState(
16315                            requiredUid, args);
16316
16317                    mPendingVerification.append(verificationId, verificationState);
16318
16319                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16320                            receivers, verificationState);
16321
16322                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16323                    final long idleDuration = getVerificationTimeout();
16324
16325                    /*
16326                     * If any sufficient verifiers were listed in the package
16327                     * manifest, attempt to ask them.
16328                     */
16329                    if (sufficientVerifiers != null) {
16330                        final int N = sufficientVerifiers.size();
16331                        if (N == 0) {
16332                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16333                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16334                        } else {
16335                            for (int i = 0; i < N; i++) {
16336                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16337                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16338                                        verifierComponent.getPackageName(), idleDuration,
16339                                        verifierUser.getIdentifier(), false, "package verifier");
16340
16341                                final Intent sufficientIntent = new Intent(verification);
16342                                sufficientIntent.setComponent(verifierComponent);
16343                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16344                            }
16345                        }
16346                    }
16347
16348                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16349                            mRequiredVerifierPackage, receivers);
16350                    if (ret == PackageManager.INSTALL_SUCCEEDED
16351                            && mRequiredVerifierPackage != null) {
16352                        Trace.asyncTraceBegin(
16353                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16354                        /*
16355                         * Send the intent to the required verification agent,
16356                         * but only start the verification timeout after the
16357                         * target BroadcastReceivers have run.
16358                         */
16359                        verification.setComponent(requiredVerifierComponent);
16360                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16361                                mRequiredVerifierPackage, idleDuration,
16362                                verifierUser.getIdentifier(), false, "package verifier");
16363                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16364                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16365                                new BroadcastReceiver() {
16366                                    @Override
16367                                    public void onReceive(Context context, Intent intent) {
16368                                        final Message msg = mHandler
16369                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16370                                        msg.arg1 = verificationId;
16371                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16372                                    }
16373                                }, null, 0, null, null);
16374
16375                        /*
16376                         * We don't want the copy to proceed until verification
16377                         * succeeds, so null out this field.
16378                         */
16379                        mArgs = null;
16380                    }
16381                } else {
16382                    /*
16383                     * No package verification is enabled, so immediately start
16384                     * the remote call to initiate copy using temporary file.
16385                     */
16386                    ret = args.copyApk(mContainerService, true);
16387                }
16388            }
16389
16390            mRet = ret;
16391        }
16392
16393        @Override
16394        void handleReturnCode() {
16395            // If mArgs is null, then MCS couldn't be reached. When it
16396            // reconnects, it will try again to install. At that point, this
16397            // will succeed.
16398            if (mArgs != null) {
16399                processPendingInstall(mArgs, mRet);
16400            }
16401        }
16402
16403        @Override
16404        void handleServiceError() {
16405            mArgs = createInstallArgs(this);
16406            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16407        }
16408
16409        public boolean isForwardLocked() {
16410            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16411        }
16412    }
16413
16414    /**
16415     * Used during creation of InstallArgs
16416     *
16417     * @param installFlags package installation flags
16418     * @return true if should be installed on external storage
16419     */
16420    private static boolean installOnExternalAsec(int installFlags) {
16421        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16422            return false;
16423        }
16424        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16425            return true;
16426        }
16427        return false;
16428    }
16429
16430    /**
16431     * Used during creation of InstallArgs
16432     *
16433     * @param installFlags package installation flags
16434     * @return true if should be installed as forward locked
16435     */
16436    private static boolean installForwardLocked(int installFlags) {
16437        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16438    }
16439
16440    private InstallArgs createInstallArgs(InstallParams params) {
16441        if (params.move != null) {
16442            return new MoveInstallArgs(params);
16443        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16444            return new AsecInstallArgs(params);
16445        } else {
16446            return new FileInstallArgs(params);
16447        }
16448    }
16449
16450    /**
16451     * Create args that describe an existing installed package. Typically used
16452     * when cleaning up old installs, or used as a move source.
16453     */
16454    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16455            String resourcePath, String[] instructionSets) {
16456        final boolean isInAsec;
16457        if (installOnExternalAsec(installFlags)) {
16458            /* Apps on SD card are always in ASEC containers. */
16459            isInAsec = true;
16460        } else if (installForwardLocked(installFlags)
16461                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16462            /*
16463             * Forward-locked apps are only in ASEC containers if they're the
16464             * new style
16465             */
16466            isInAsec = true;
16467        } else {
16468            isInAsec = false;
16469        }
16470
16471        if (isInAsec) {
16472            return new AsecInstallArgs(codePath, instructionSets,
16473                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16474        } else {
16475            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16476        }
16477    }
16478
16479    static abstract class InstallArgs {
16480        /** @see InstallParams#origin */
16481        final OriginInfo origin;
16482        /** @see InstallParams#move */
16483        final MoveInfo move;
16484
16485        final IPackageInstallObserver2 observer;
16486        // Always refers to PackageManager flags only
16487        final int installFlags;
16488        final String installerPackageName;
16489        final String volumeUuid;
16490        final UserHandle user;
16491        final String abiOverride;
16492        final String[] installGrantPermissions;
16493        /** If non-null, drop an async trace when the install completes */
16494        final String traceMethod;
16495        final int traceCookie;
16496        final Certificate[][] certificates;
16497        final int installReason;
16498
16499        // The list of instruction sets supported by this app. This is currently
16500        // only used during the rmdex() phase to clean up resources. We can get rid of this
16501        // if we move dex files under the common app path.
16502        /* nullable */ String[] instructionSets;
16503
16504        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16505                int installFlags, String installerPackageName, String volumeUuid,
16506                UserHandle user, String[] instructionSets,
16507                String abiOverride, String[] installGrantPermissions,
16508                String traceMethod, int traceCookie, Certificate[][] certificates,
16509                int installReason) {
16510            this.origin = origin;
16511            this.move = move;
16512            this.installFlags = installFlags;
16513            this.observer = observer;
16514            this.installerPackageName = installerPackageName;
16515            this.volumeUuid = volumeUuid;
16516            this.user = user;
16517            this.instructionSets = instructionSets;
16518            this.abiOverride = abiOverride;
16519            this.installGrantPermissions = installGrantPermissions;
16520            this.traceMethod = traceMethod;
16521            this.traceCookie = traceCookie;
16522            this.certificates = certificates;
16523            this.installReason = installReason;
16524        }
16525
16526        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16527        abstract int doPreInstall(int status);
16528
16529        /**
16530         * Rename package into final resting place. All paths on the given
16531         * scanned package should be updated to reflect the rename.
16532         */
16533        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16534        abstract int doPostInstall(int status, int uid);
16535
16536        /** @see PackageSettingBase#codePathString */
16537        abstract String getCodePath();
16538        /** @see PackageSettingBase#resourcePathString */
16539        abstract String getResourcePath();
16540
16541        // Need installer lock especially for dex file removal.
16542        abstract void cleanUpResourcesLI();
16543        abstract boolean doPostDeleteLI(boolean delete);
16544
16545        /**
16546         * Called before the source arguments are copied. This is used mostly
16547         * for MoveParams when it needs to read the source file to put it in the
16548         * destination.
16549         */
16550        int doPreCopy() {
16551            return PackageManager.INSTALL_SUCCEEDED;
16552        }
16553
16554        /**
16555         * Called after the source arguments are copied. This is used mostly for
16556         * MoveParams when it needs to read the source file to put it in the
16557         * destination.
16558         */
16559        int doPostCopy(int uid) {
16560            return PackageManager.INSTALL_SUCCEEDED;
16561        }
16562
16563        protected boolean isFwdLocked() {
16564            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16565        }
16566
16567        protected boolean isExternalAsec() {
16568            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16569        }
16570
16571        protected boolean isEphemeral() {
16572            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16573        }
16574
16575        UserHandle getUser() {
16576            return user;
16577        }
16578    }
16579
16580    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16581        if (!allCodePaths.isEmpty()) {
16582            if (instructionSets == null) {
16583                throw new IllegalStateException("instructionSet == null");
16584            }
16585            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16586            for (String codePath : allCodePaths) {
16587                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16588                    try {
16589                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16590                    } catch (InstallerException ignored) {
16591                    }
16592                }
16593            }
16594        }
16595    }
16596
16597    /**
16598     * Logic to handle installation of non-ASEC applications, including copying
16599     * and renaming logic.
16600     */
16601    class FileInstallArgs extends InstallArgs {
16602        private File codeFile;
16603        private File resourceFile;
16604
16605        // Example topology:
16606        // /data/app/com.example/base.apk
16607        // /data/app/com.example/split_foo.apk
16608        // /data/app/com.example/lib/arm/libfoo.so
16609        // /data/app/com.example/lib/arm64/libfoo.so
16610        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16611
16612        /** New install */
16613        FileInstallArgs(InstallParams params) {
16614            super(params.origin, params.move, params.observer, params.installFlags,
16615                    params.installerPackageName, params.volumeUuid,
16616                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16617                    params.grantedRuntimePermissions,
16618                    params.traceMethod, params.traceCookie, params.certificates,
16619                    params.installReason);
16620            if (isFwdLocked()) {
16621                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16622            }
16623        }
16624
16625        /** Existing install */
16626        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16627            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16628                    null, null, null, 0, null /*certificates*/,
16629                    PackageManager.INSTALL_REASON_UNKNOWN);
16630            this.codeFile = (codePath != null) ? new File(codePath) : null;
16631            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16632        }
16633
16634        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16635            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16636            try {
16637                return doCopyApk(imcs, temp);
16638            } finally {
16639                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16640            }
16641        }
16642
16643        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16644            if (origin.staged) {
16645                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16646                codeFile = origin.file;
16647                resourceFile = origin.file;
16648                return PackageManager.INSTALL_SUCCEEDED;
16649            }
16650
16651            try {
16652                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16653                final File tempDir =
16654                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16655                codeFile = tempDir;
16656                resourceFile = tempDir;
16657            } catch (IOException e) {
16658                Slog.w(TAG, "Failed to create copy file: " + e);
16659                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16660            }
16661
16662            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16663                @Override
16664                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16665                    if (!FileUtils.isValidExtFilename(name)) {
16666                        throw new IllegalArgumentException("Invalid filename: " + name);
16667                    }
16668                    try {
16669                        final File file = new File(codeFile, name);
16670                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16671                                O_RDWR | O_CREAT, 0644);
16672                        Os.chmod(file.getAbsolutePath(), 0644);
16673                        return new ParcelFileDescriptor(fd);
16674                    } catch (ErrnoException e) {
16675                        throw new RemoteException("Failed to open: " + e.getMessage());
16676                    }
16677                }
16678            };
16679
16680            int ret = PackageManager.INSTALL_SUCCEEDED;
16681            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16682            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16683                Slog.e(TAG, "Failed to copy package");
16684                return ret;
16685            }
16686
16687            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16688            NativeLibraryHelper.Handle handle = null;
16689            try {
16690                handle = NativeLibraryHelper.Handle.create(codeFile);
16691                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16692                        abiOverride);
16693            } catch (IOException e) {
16694                Slog.e(TAG, "Copying native libraries failed", e);
16695                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16696            } finally {
16697                IoUtils.closeQuietly(handle);
16698            }
16699
16700            return ret;
16701        }
16702
16703        int doPreInstall(int status) {
16704            if (status != PackageManager.INSTALL_SUCCEEDED) {
16705                cleanUp();
16706            }
16707            return status;
16708        }
16709
16710        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16711            if (status != PackageManager.INSTALL_SUCCEEDED) {
16712                cleanUp();
16713                return false;
16714            }
16715
16716            final File targetDir = codeFile.getParentFile();
16717            final File beforeCodeFile = codeFile;
16718            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16719
16720            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16721            try {
16722                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16723            } catch (ErrnoException e) {
16724                Slog.w(TAG, "Failed to rename", e);
16725                return false;
16726            }
16727
16728            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16729                Slog.w(TAG, "Failed to restorecon");
16730                return false;
16731            }
16732
16733            // Reflect the rename internally
16734            codeFile = afterCodeFile;
16735            resourceFile = afterCodeFile;
16736
16737            // Reflect the rename in scanned details
16738            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16739            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16740                    afterCodeFile, pkg.baseCodePath));
16741            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16742                    afterCodeFile, pkg.splitCodePaths));
16743
16744            // Reflect the rename in app info
16745            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16746            pkg.setApplicationInfoCodePath(pkg.codePath);
16747            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16748            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16749            pkg.setApplicationInfoResourcePath(pkg.codePath);
16750            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16751            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16752
16753            return true;
16754        }
16755
16756        int doPostInstall(int status, int uid) {
16757            if (status != PackageManager.INSTALL_SUCCEEDED) {
16758                cleanUp();
16759            }
16760            return status;
16761        }
16762
16763        @Override
16764        String getCodePath() {
16765            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16766        }
16767
16768        @Override
16769        String getResourcePath() {
16770            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16771        }
16772
16773        private boolean cleanUp() {
16774            if (codeFile == null || !codeFile.exists()) {
16775                return false;
16776            }
16777
16778            removeCodePathLI(codeFile);
16779
16780            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16781                resourceFile.delete();
16782            }
16783
16784            return true;
16785        }
16786
16787        void cleanUpResourcesLI() {
16788            // Try enumerating all code paths before deleting
16789            List<String> allCodePaths = Collections.EMPTY_LIST;
16790            if (codeFile != null && codeFile.exists()) {
16791                try {
16792                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16793                    allCodePaths = pkg.getAllCodePaths();
16794                } catch (PackageParserException e) {
16795                    // Ignored; we tried our best
16796                }
16797            }
16798
16799            cleanUp();
16800            removeDexFiles(allCodePaths, instructionSets);
16801        }
16802
16803        boolean doPostDeleteLI(boolean delete) {
16804            // XXX err, shouldn't we respect the delete flag?
16805            cleanUpResourcesLI();
16806            return true;
16807        }
16808    }
16809
16810    private boolean isAsecExternal(String cid) {
16811        final String asecPath = PackageHelper.getSdFilesystem(cid);
16812        return !asecPath.startsWith(mAsecInternalPath);
16813    }
16814
16815    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16816            PackageManagerException {
16817        if (copyRet < 0) {
16818            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16819                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16820                throw new PackageManagerException(copyRet, message);
16821            }
16822        }
16823    }
16824
16825    /**
16826     * Extract the StorageManagerService "container ID" from the full code path of an
16827     * .apk.
16828     */
16829    static String cidFromCodePath(String fullCodePath) {
16830        int eidx = fullCodePath.lastIndexOf("/");
16831        String subStr1 = fullCodePath.substring(0, eidx);
16832        int sidx = subStr1.lastIndexOf("/");
16833        return subStr1.substring(sidx+1, eidx);
16834    }
16835
16836    /**
16837     * Logic to handle installation of ASEC applications, including copying and
16838     * renaming logic.
16839     */
16840    class AsecInstallArgs extends InstallArgs {
16841        static final String RES_FILE_NAME = "pkg.apk";
16842        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16843
16844        String cid;
16845        String packagePath;
16846        String resourcePath;
16847
16848        /** New install */
16849        AsecInstallArgs(InstallParams params) {
16850            super(params.origin, params.move, params.observer, params.installFlags,
16851                    params.installerPackageName, params.volumeUuid,
16852                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16853                    params.grantedRuntimePermissions,
16854                    params.traceMethod, params.traceCookie, params.certificates,
16855                    params.installReason);
16856        }
16857
16858        /** Existing install */
16859        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16860                        boolean isExternal, boolean isForwardLocked) {
16861            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16862                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16863                    instructionSets, null, null, null, 0, null /*certificates*/,
16864                    PackageManager.INSTALL_REASON_UNKNOWN);
16865            // Hackily pretend we're still looking at a full code path
16866            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16867                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16868            }
16869
16870            // Extract cid from fullCodePath
16871            int eidx = fullCodePath.lastIndexOf("/");
16872            String subStr1 = fullCodePath.substring(0, eidx);
16873            int sidx = subStr1.lastIndexOf("/");
16874            cid = subStr1.substring(sidx+1, eidx);
16875            setMountPath(subStr1);
16876        }
16877
16878        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16879            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16880                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16881                    instructionSets, null, null, null, 0, null /*certificates*/,
16882                    PackageManager.INSTALL_REASON_UNKNOWN);
16883            this.cid = cid;
16884            setMountPath(PackageHelper.getSdDir(cid));
16885        }
16886
16887        void createCopyFile() {
16888            cid = mInstallerService.allocateExternalStageCidLegacy();
16889        }
16890
16891        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16892            if (origin.staged && origin.cid != null) {
16893                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16894                cid = origin.cid;
16895                setMountPath(PackageHelper.getSdDir(cid));
16896                return PackageManager.INSTALL_SUCCEEDED;
16897            }
16898
16899            if (temp) {
16900                createCopyFile();
16901            } else {
16902                /*
16903                 * Pre-emptively destroy the container since it's destroyed if
16904                 * copying fails due to it existing anyway.
16905                 */
16906                PackageHelper.destroySdDir(cid);
16907            }
16908
16909            final String newMountPath = imcs.copyPackageToContainer(
16910                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16911                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16912
16913            if (newMountPath != null) {
16914                setMountPath(newMountPath);
16915                return PackageManager.INSTALL_SUCCEEDED;
16916            } else {
16917                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16918            }
16919        }
16920
16921        @Override
16922        String getCodePath() {
16923            return packagePath;
16924        }
16925
16926        @Override
16927        String getResourcePath() {
16928            return resourcePath;
16929        }
16930
16931        int doPreInstall(int status) {
16932            if (status != PackageManager.INSTALL_SUCCEEDED) {
16933                // Destroy container
16934                PackageHelper.destroySdDir(cid);
16935            } else {
16936                boolean mounted = PackageHelper.isContainerMounted(cid);
16937                if (!mounted) {
16938                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16939                            Process.SYSTEM_UID);
16940                    if (newMountPath != null) {
16941                        setMountPath(newMountPath);
16942                    } else {
16943                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16944                    }
16945                }
16946            }
16947            return status;
16948        }
16949
16950        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16951            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16952            String newMountPath = null;
16953            if (PackageHelper.isContainerMounted(cid)) {
16954                // Unmount the container
16955                if (!PackageHelper.unMountSdDir(cid)) {
16956                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16957                    return false;
16958                }
16959            }
16960            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16961                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16962                        " which might be stale. Will try to clean up.");
16963                // Clean up the stale container and proceed to recreate.
16964                if (!PackageHelper.destroySdDir(newCacheId)) {
16965                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16966                    return false;
16967                }
16968                // Successfully cleaned up stale container. Try to rename again.
16969                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16970                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16971                            + " inspite of cleaning it up.");
16972                    return false;
16973                }
16974            }
16975            if (!PackageHelper.isContainerMounted(newCacheId)) {
16976                Slog.w(TAG, "Mounting container " + newCacheId);
16977                newMountPath = PackageHelper.mountSdDir(newCacheId,
16978                        getEncryptKey(), Process.SYSTEM_UID);
16979            } else {
16980                newMountPath = PackageHelper.getSdDir(newCacheId);
16981            }
16982            if (newMountPath == null) {
16983                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16984                return false;
16985            }
16986            Log.i(TAG, "Succesfully renamed " + cid +
16987                    " to " + newCacheId +
16988                    " at new path: " + newMountPath);
16989            cid = newCacheId;
16990
16991            final File beforeCodeFile = new File(packagePath);
16992            setMountPath(newMountPath);
16993            final File afterCodeFile = new File(packagePath);
16994
16995            // Reflect the rename in scanned details
16996            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16997            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16998                    afterCodeFile, pkg.baseCodePath));
16999            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17000                    afterCodeFile, pkg.splitCodePaths));
17001
17002            // Reflect the rename in app info
17003            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17004            pkg.setApplicationInfoCodePath(pkg.codePath);
17005            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17006            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17007            pkg.setApplicationInfoResourcePath(pkg.codePath);
17008            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17009            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17010
17011            return true;
17012        }
17013
17014        private void setMountPath(String mountPath) {
17015            final File mountFile = new File(mountPath);
17016
17017            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17018            if (monolithicFile.exists()) {
17019                packagePath = monolithicFile.getAbsolutePath();
17020                if (isFwdLocked()) {
17021                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17022                } else {
17023                    resourcePath = packagePath;
17024                }
17025            } else {
17026                packagePath = mountFile.getAbsolutePath();
17027                resourcePath = packagePath;
17028            }
17029        }
17030
17031        int doPostInstall(int status, int uid) {
17032            if (status != PackageManager.INSTALL_SUCCEEDED) {
17033                cleanUp();
17034            } else {
17035                final int groupOwner;
17036                final String protectedFile;
17037                if (isFwdLocked()) {
17038                    groupOwner = UserHandle.getSharedAppGid(uid);
17039                    protectedFile = RES_FILE_NAME;
17040                } else {
17041                    groupOwner = -1;
17042                    protectedFile = null;
17043                }
17044
17045                if (uid < Process.FIRST_APPLICATION_UID
17046                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17047                    Slog.e(TAG, "Failed to finalize " + cid);
17048                    PackageHelper.destroySdDir(cid);
17049                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17050                }
17051
17052                boolean mounted = PackageHelper.isContainerMounted(cid);
17053                if (!mounted) {
17054                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17055                }
17056            }
17057            return status;
17058        }
17059
17060        private void cleanUp() {
17061            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17062
17063            // Destroy secure container
17064            PackageHelper.destroySdDir(cid);
17065        }
17066
17067        private List<String> getAllCodePaths() {
17068            final File codeFile = new File(getCodePath());
17069            if (codeFile != null && codeFile.exists()) {
17070                try {
17071                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17072                    return pkg.getAllCodePaths();
17073                } catch (PackageParserException e) {
17074                    // Ignored; we tried our best
17075                }
17076            }
17077            return Collections.EMPTY_LIST;
17078        }
17079
17080        void cleanUpResourcesLI() {
17081            // Enumerate all code paths before deleting
17082            cleanUpResourcesLI(getAllCodePaths());
17083        }
17084
17085        private void cleanUpResourcesLI(List<String> allCodePaths) {
17086            cleanUp();
17087            removeDexFiles(allCodePaths, instructionSets);
17088        }
17089
17090        String getPackageName() {
17091            return getAsecPackageName(cid);
17092        }
17093
17094        boolean doPostDeleteLI(boolean delete) {
17095            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17096            final List<String> allCodePaths = getAllCodePaths();
17097            boolean mounted = PackageHelper.isContainerMounted(cid);
17098            if (mounted) {
17099                // Unmount first
17100                if (PackageHelper.unMountSdDir(cid)) {
17101                    mounted = false;
17102                }
17103            }
17104            if (!mounted && delete) {
17105                cleanUpResourcesLI(allCodePaths);
17106            }
17107            return !mounted;
17108        }
17109
17110        @Override
17111        int doPreCopy() {
17112            if (isFwdLocked()) {
17113                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17114                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17115                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17116                }
17117            }
17118
17119            return PackageManager.INSTALL_SUCCEEDED;
17120        }
17121
17122        @Override
17123        int doPostCopy(int uid) {
17124            if (isFwdLocked()) {
17125                if (uid < Process.FIRST_APPLICATION_UID
17126                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17127                                RES_FILE_NAME)) {
17128                    Slog.e(TAG, "Failed to finalize " + cid);
17129                    PackageHelper.destroySdDir(cid);
17130                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17131                }
17132            }
17133
17134            return PackageManager.INSTALL_SUCCEEDED;
17135        }
17136    }
17137
17138    /**
17139     * Logic to handle movement of existing installed applications.
17140     */
17141    class MoveInstallArgs extends InstallArgs {
17142        private File codeFile;
17143        private File resourceFile;
17144
17145        /** New install */
17146        MoveInstallArgs(InstallParams params) {
17147            super(params.origin, params.move, params.observer, params.installFlags,
17148                    params.installerPackageName, params.volumeUuid,
17149                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17150                    params.grantedRuntimePermissions,
17151                    params.traceMethod, params.traceCookie, params.certificates,
17152                    params.installReason);
17153        }
17154
17155        int copyApk(IMediaContainerService imcs, boolean temp) {
17156            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17157                    + move.fromUuid + " to " + move.toUuid);
17158            synchronized (mInstaller) {
17159                try {
17160                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17161                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17162                } catch (InstallerException e) {
17163                    Slog.w(TAG, "Failed to move app", e);
17164                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17165                }
17166            }
17167
17168            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17169            resourceFile = codeFile;
17170            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17171
17172            return PackageManager.INSTALL_SUCCEEDED;
17173        }
17174
17175        int doPreInstall(int status) {
17176            if (status != PackageManager.INSTALL_SUCCEEDED) {
17177                cleanUp(move.toUuid);
17178            }
17179            return status;
17180        }
17181
17182        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17183            if (status != PackageManager.INSTALL_SUCCEEDED) {
17184                cleanUp(move.toUuid);
17185                return false;
17186            }
17187
17188            // Reflect the move in app info
17189            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17190            pkg.setApplicationInfoCodePath(pkg.codePath);
17191            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17192            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17193            pkg.setApplicationInfoResourcePath(pkg.codePath);
17194            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17195            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17196
17197            return true;
17198        }
17199
17200        int doPostInstall(int status, int uid) {
17201            if (status == PackageManager.INSTALL_SUCCEEDED) {
17202                cleanUp(move.fromUuid);
17203            } else {
17204                cleanUp(move.toUuid);
17205            }
17206            return status;
17207        }
17208
17209        @Override
17210        String getCodePath() {
17211            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17212        }
17213
17214        @Override
17215        String getResourcePath() {
17216            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17217        }
17218
17219        private boolean cleanUp(String volumeUuid) {
17220            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17221                    move.dataAppName);
17222            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17223            final int[] userIds = sUserManager.getUserIds();
17224            synchronized (mInstallLock) {
17225                // Clean up both app data and code
17226                // All package moves are frozen until finished
17227                for (int userId : userIds) {
17228                    try {
17229                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17230                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17231                    } catch (InstallerException e) {
17232                        Slog.w(TAG, String.valueOf(e));
17233                    }
17234                }
17235                removeCodePathLI(codeFile);
17236            }
17237            return true;
17238        }
17239
17240        void cleanUpResourcesLI() {
17241            throw new UnsupportedOperationException();
17242        }
17243
17244        boolean doPostDeleteLI(boolean delete) {
17245            throw new UnsupportedOperationException();
17246        }
17247    }
17248
17249    static String getAsecPackageName(String packageCid) {
17250        int idx = packageCid.lastIndexOf("-");
17251        if (idx == -1) {
17252            return packageCid;
17253        }
17254        return packageCid.substring(0, idx);
17255    }
17256
17257    // Utility method used to create code paths based on package name and available index.
17258    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17259        String idxStr = "";
17260        int idx = 1;
17261        // Fall back to default value of idx=1 if prefix is not
17262        // part of oldCodePath
17263        if (oldCodePath != null) {
17264            String subStr = oldCodePath;
17265            // Drop the suffix right away
17266            if (suffix != null && subStr.endsWith(suffix)) {
17267                subStr = subStr.substring(0, subStr.length() - suffix.length());
17268            }
17269            // If oldCodePath already contains prefix find out the
17270            // ending index to either increment or decrement.
17271            int sidx = subStr.lastIndexOf(prefix);
17272            if (sidx != -1) {
17273                subStr = subStr.substring(sidx + prefix.length());
17274                if (subStr != null) {
17275                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17276                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17277                    }
17278                    try {
17279                        idx = Integer.parseInt(subStr);
17280                        if (idx <= 1) {
17281                            idx++;
17282                        } else {
17283                            idx--;
17284                        }
17285                    } catch(NumberFormatException e) {
17286                    }
17287                }
17288            }
17289        }
17290        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17291        return prefix + idxStr;
17292    }
17293
17294    private File getNextCodePath(File targetDir, String packageName) {
17295        File result;
17296        SecureRandom random = new SecureRandom();
17297        byte[] bytes = new byte[16];
17298        do {
17299            random.nextBytes(bytes);
17300            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17301            result = new File(targetDir, packageName + "-" + suffix);
17302        } while (result.exists());
17303        return result;
17304    }
17305
17306    // Utility method that returns the relative package path with respect
17307    // to the installation directory. Like say for /data/data/com.test-1.apk
17308    // string com.test-1 is returned.
17309    static String deriveCodePathName(String codePath) {
17310        if (codePath == null) {
17311            return null;
17312        }
17313        final File codeFile = new File(codePath);
17314        final String name = codeFile.getName();
17315        if (codeFile.isDirectory()) {
17316            return name;
17317        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17318            final int lastDot = name.lastIndexOf('.');
17319            return name.substring(0, lastDot);
17320        } else {
17321            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17322            return null;
17323        }
17324    }
17325
17326    static class PackageInstalledInfo {
17327        String name;
17328        int uid;
17329        // The set of users that originally had this package installed.
17330        int[] origUsers;
17331        // The set of users that now have this package installed.
17332        int[] newUsers;
17333        PackageParser.Package pkg;
17334        int returnCode;
17335        String returnMsg;
17336        String installerPackageName;
17337        PackageRemovedInfo removedInfo;
17338        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17339
17340        public void setError(int code, String msg) {
17341            setReturnCode(code);
17342            setReturnMessage(msg);
17343            Slog.w(TAG, msg);
17344        }
17345
17346        public void setError(String msg, PackageParserException e) {
17347            setReturnCode(e.error);
17348            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17349            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17350            for (int i = 0; i < childCount; i++) {
17351                addedChildPackages.valueAt(i).setError(msg, e);
17352            }
17353            Slog.w(TAG, msg, e);
17354        }
17355
17356        public void setError(String msg, PackageManagerException e) {
17357            returnCode = e.error;
17358            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17359            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17360            for (int i = 0; i < childCount; i++) {
17361                addedChildPackages.valueAt(i).setError(msg, e);
17362            }
17363            Slog.w(TAG, msg, e);
17364        }
17365
17366        public void setReturnCode(int returnCode) {
17367            this.returnCode = returnCode;
17368            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17369            for (int i = 0; i < childCount; i++) {
17370                addedChildPackages.valueAt(i).returnCode = returnCode;
17371            }
17372        }
17373
17374        private void setReturnMessage(String returnMsg) {
17375            this.returnMsg = returnMsg;
17376            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17377            for (int i = 0; i < childCount; i++) {
17378                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17379            }
17380        }
17381
17382        // In some error cases we want to convey more info back to the observer
17383        String origPackage;
17384        String origPermission;
17385    }
17386
17387    /*
17388     * Install a non-existing package.
17389     */
17390    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17391            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17392            PackageInstalledInfo res, int installReason) {
17393        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17394
17395        // Remember this for later, in case we need to rollback this install
17396        String pkgName = pkg.packageName;
17397
17398        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17399
17400        synchronized(mPackages) {
17401            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17402            if (renamedPackage != null) {
17403                // A package with the same name is already installed, though
17404                // it has been renamed to an older name.  The package we
17405                // are trying to install should be installed as an update to
17406                // the existing one, but that has not been requested, so bail.
17407                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17408                        + " without first uninstalling package running as "
17409                        + renamedPackage);
17410                return;
17411            }
17412            if (mPackages.containsKey(pkgName)) {
17413                // Don't allow installation over an existing package with the same name.
17414                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17415                        + " without first uninstalling.");
17416                return;
17417            }
17418        }
17419
17420        try {
17421            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17422                    System.currentTimeMillis(), user);
17423
17424            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17425
17426            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17427                prepareAppDataAfterInstallLIF(newPackage);
17428
17429            } else {
17430                // Remove package from internal structures, but keep around any
17431                // data that might have already existed
17432                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17433                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17434            }
17435        } catch (PackageManagerException e) {
17436            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17437        }
17438
17439        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17440    }
17441
17442    private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) {
17443        // Can't rotate keys during boot or if sharedUser.
17444        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser()
17445                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17446            return false;
17447        }
17448        // app is using upgradeKeySets; make sure all are valid
17449        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17450        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17451        for (int i = 0; i < upgradeKeySets.length; i++) {
17452            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17453                Slog.wtf(TAG, "Package "
17454                         + (oldPs.name != null ? oldPs.name : "<null>")
17455                         + " contains upgrade-key-set reference to unknown key-set: "
17456                         + upgradeKeySets[i]
17457                         + " reverting to signatures check.");
17458                return false;
17459            }
17460        }
17461        return true;
17462    }
17463
17464    private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) {
17465        // Upgrade keysets are being used.  Determine if new package has a superset of the
17466        // required keys.
17467        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17468        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17469        for (int i = 0; i < upgradeKeySets.length; i++) {
17470            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17471            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17472                return true;
17473            }
17474        }
17475        return false;
17476    }
17477
17478    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17479        try (DigestInputStream digestStream =
17480                new DigestInputStream(new FileInputStream(file), digest)) {
17481            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17482        }
17483    }
17484
17485    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17486            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17487            int installReason) {
17488        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17489
17490        final PackageParser.Package oldPackage;
17491        final PackageSetting ps;
17492        final String pkgName = pkg.packageName;
17493        final int[] allUsers;
17494        final int[] installedUsers;
17495
17496        synchronized(mPackages) {
17497            oldPackage = mPackages.get(pkgName);
17498            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17499
17500            // don't allow upgrade to target a release SDK from a pre-release SDK
17501            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17502                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17503            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17504                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17505            if (oldTargetsPreRelease
17506                    && !newTargetsPreRelease
17507                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17508                Slog.w(TAG, "Can't install package targeting released sdk");
17509                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17510                return;
17511            }
17512
17513            ps = mSettings.mPackages.get(pkgName);
17514
17515            // verify signatures are valid
17516            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17517                if (!checkUpgradeKeySetLP(ps, pkg)) {
17518                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17519                            "New package not signed by keys specified by upgrade-keysets: "
17520                                    + pkgName);
17521                    return;
17522                }
17523            } else {
17524                // default to original signature matching
17525                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17526                        != PackageManager.SIGNATURE_MATCH) {
17527                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17528                            "New package has a different signature: " + pkgName);
17529                    return;
17530                }
17531            }
17532
17533            // don't allow a system upgrade unless the upgrade hash matches
17534            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17535                byte[] digestBytes = null;
17536                try {
17537                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17538                    updateDigest(digest, new File(pkg.baseCodePath));
17539                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17540                        for (String path : pkg.splitCodePaths) {
17541                            updateDigest(digest, new File(path));
17542                        }
17543                    }
17544                    digestBytes = digest.digest();
17545                } catch (NoSuchAlgorithmException | IOException e) {
17546                    res.setError(INSTALL_FAILED_INVALID_APK,
17547                            "Could not compute hash: " + pkgName);
17548                    return;
17549                }
17550                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17551                    res.setError(INSTALL_FAILED_INVALID_APK,
17552                            "New package fails restrict-update check: " + pkgName);
17553                    return;
17554                }
17555                // retain upgrade restriction
17556                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17557            }
17558
17559            // Check for shared user id changes
17560            String invalidPackageName =
17561                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17562            if (invalidPackageName != null) {
17563                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17564                        "Package " + invalidPackageName + " tried to change user "
17565                                + oldPackage.mSharedUserId);
17566                return;
17567            }
17568
17569            // In case of rollback, remember per-user/profile install state
17570            allUsers = sUserManager.getUserIds();
17571            installedUsers = ps.queryInstalledUsers(allUsers, true);
17572
17573            // don't allow an upgrade from full to ephemeral
17574            if (isInstantApp) {
17575                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17576                    for (int currentUser : allUsers) {
17577                        if (!ps.getInstantApp(currentUser)) {
17578                            // can't downgrade from full to instant
17579                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17580                                    + " for user: " + currentUser);
17581                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17582                            return;
17583                        }
17584                    }
17585                } else if (!ps.getInstantApp(user.getIdentifier())) {
17586                    // can't downgrade from full to instant
17587                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17588                            + " for user: " + user.getIdentifier());
17589                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17590                    return;
17591                }
17592            }
17593        }
17594
17595        // Update what is removed
17596        res.removedInfo = new PackageRemovedInfo(this);
17597        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17598        res.removedInfo.removedPackage = oldPackage.packageName;
17599        res.removedInfo.installerPackageName = ps.installerPackageName;
17600        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17601        res.removedInfo.isUpdate = true;
17602        res.removedInfo.origUsers = installedUsers;
17603        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17604        for (int i = 0; i < installedUsers.length; i++) {
17605            final int userId = installedUsers[i];
17606            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17607        }
17608
17609        final int childCount = (oldPackage.childPackages != null)
17610                ? oldPackage.childPackages.size() : 0;
17611        for (int i = 0; i < childCount; i++) {
17612            boolean childPackageUpdated = false;
17613            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17614            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17615            if (res.addedChildPackages != null) {
17616                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17617                if (childRes != null) {
17618                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17619                    childRes.removedInfo.removedPackage = childPkg.packageName;
17620                    if (childPs != null) {
17621                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17622                    }
17623                    childRes.removedInfo.isUpdate = true;
17624                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17625                    childPackageUpdated = true;
17626                }
17627            }
17628            if (!childPackageUpdated) {
17629                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17630                childRemovedRes.removedPackage = childPkg.packageName;
17631                if (childPs != null) {
17632                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17633                }
17634                childRemovedRes.isUpdate = false;
17635                childRemovedRes.dataRemoved = true;
17636                synchronized (mPackages) {
17637                    if (childPs != null) {
17638                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17639                    }
17640                }
17641                if (res.removedInfo.removedChildPackages == null) {
17642                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17643                }
17644                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17645            }
17646        }
17647
17648        boolean sysPkg = (isSystemApp(oldPackage));
17649        if (sysPkg) {
17650            // Set the system/privileged/oem flags as needed
17651            final boolean privileged =
17652                    (oldPackage.applicationInfo.privateFlags
17653                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17654            final boolean oem =
17655                    (oldPackage.applicationInfo.privateFlags
17656                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17657            final int systemPolicyFlags = policyFlags
17658                    | PackageParser.PARSE_IS_SYSTEM
17659                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
17660                    | (oem ? PARSE_IS_OEM : 0);
17661
17662            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17663                    user, allUsers, installerPackageName, res, installReason);
17664        } else {
17665            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17666                    user, allUsers, installerPackageName, res, installReason);
17667        }
17668    }
17669
17670    @Override
17671    public List<String> getPreviousCodePaths(String packageName) {
17672        final int callingUid = Binder.getCallingUid();
17673        final List<String> result = new ArrayList<>();
17674        if (getInstantAppPackageName(callingUid) != null) {
17675            return result;
17676        }
17677        final PackageSetting ps = mSettings.mPackages.get(packageName);
17678        if (ps != null
17679                && ps.oldCodePaths != null
17680                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17681            result.addAll(ps.oldCodePaths);
17682        }
17683        return result;
17684    }
17685
17686    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17687            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17688            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17689            int installReason) {
17690        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17691                + deletedPackage);
17692
17693        String pkgName = deletedPackage.packageName;
17694        boolean deletedPkg = true;
17695        boolean addedPkg = false;
17696        boolean updatedSettings = false;
17697        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17698        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17699                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17700
17701        final long origUpdateTime = (pkg.mExtras != null)
17702                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17703
17704        // First delete the existing package while retaining the data directory
17705        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17706                res.removedInfo, true, pkg)) {
17707            // If the existing package wasn't successfully deleted
17708            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17709            deletedPkg = false;
17710        } else {
17711            // Successfully deleted the old package; proceed with replace.
17712
17713            // If deleted package lived in a container, give users a chance to
17714            // relinquish resources before killing.
17715            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17716                if (DEBUG_INSTALL) {
17717                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17718                }
17719                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17720                final ArrayList<String> pkgList = new ArrayList<String>(1);
17721                pkgList.add(deletedPackage.applicationInfo.packageName);
17722                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17723            }
17724
17725            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17726                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17727            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17728
17729            try {
17730                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17731                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17732                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17733                        installReason);
17734
17735                // Update the in-memory copy of the previous code paths.
17736                PackageSetting ps = mSettings.mPackages.get(pkgName);
17737                if (!killApp) {
17738                    if (ps.oldCodePaths == null) {
17739                        ps.oldCodePaths = new ArraySet<>();
17740                    }
17741                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17742                    if (deletedPackage.splitCodePaths != null) {
17743                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17744                    }
17745                } else {
17746                    ps.oldCodePaths = null;
17747                }
17748                if (ps.childPackageNames != null) {
17749                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17750                        final String childPkgName = ps.childPackageNames.get(i);
17751                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17752                        childPs.oldCodePaths = ps.oldCodePaths;
17753                    }
17754                }
17755                // set instant app status, but, only if it's explicitly specified
17756                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17757                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17758                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17759                prepareAppDataAfterInstallLIF(newPackage);
17760                addedPkg = true;
17761                mDexManager.notifyPackageUpdated(newPackage.packageName,
17762                        newPackage.baseCodePath, newPackage.splitCodePaths);
17763            } catch (PackageManagerException e) {
17764                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17765            }
17766        }
17767
17768        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17769            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17770
17771            // Revert all internal state mutations and added folders for the failed install
17772            if (addedPkg) {
17773                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17774                        res.removedInfo, true, null);
17775            }
17776
17777            // Restore the old package
17778            if (deletedPkg) {
17779                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17780                File restoreFile = new File(deletedPackage.codePath);
17781                // Parse old package
17782                boolean oldExternal = isExternal(deletedPackage);
17783                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17784                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17785                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17786                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17787                try {
17788                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17789                            null);
17790                } catch (PackageManagerException e) {
17791                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17792                            + e.getMessage());
17793                    return;
17794                }
17795
17796                synchronized (mPackages) {
17797                    // Ensure the installer package name up to date
17798                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17799
17800                    // Update permissions for restored package
17801                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17802
17803                    mSettings.writeLPr();
17804                }
17805
17806                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17807            }
17808        } else {
17809            synchronized (mPackages) {
17810                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17811                if (ps != null) {
17812                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17813                    if (res.removedInfo.removedChildPackages != null) {
17814                        final int childCount = res.removedInfo.removedChildPackages.size();
17815                        // Iterate in reverse as we may modify the collection
17816                        for (int i = childCount - 1; i >= 0; i--) {
17817                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17818                            if (res.addedChildPackages.containsKey(childPackageName)) {
17819                                res.removedInfo.removedChildPackages.removeAt(i);
17820                            } else {
17821                                PackageRemovedInfo childInfo = res.removedInfo
17822                                        .removedChildPackages.valueAt(i);
17823                                childInfo.removedForAllUsers = mPackages.get(
17824                                        childInfo.removedPackage) == null;
17825                            }
17826                        }
17827                    }
17828                }
17829            }
17830        }
17831    }
17832
17833    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17834            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17835            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17836            int installReason) {
17837        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17838                + ", old=" + deletedPackage);
17839
17840        final boolean disabledSystem;
17841
17842        // Remove existing system package
17843        removePackageLI(deletedPackage, true);
17844
17845        synchronized (mPackages) {
17846            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17847        }
17848        if (!disabledSystem) {
17849            // We didn't need to disable the .apk as a current system package,
17850            // which means we are replacing another update that is already
17851            // installed.  We need to make sure to delete the older one's .apk.
17852            res.removedInfo.args = createInstallArgsForExisting(0,
17853                    deletedPackage.applicationInfo.getCodePath(),
17854                    deletedPackage.applicationInfo.getResourcePath(),
17855                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17856        } else {
17857            res.removedInfo.args = null;
17858        }
17859
17860        // Successfully disabled the old package. Now proceed with re-installation
17861        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17862                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17863        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17864
17865        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17866        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17867                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17868
17869        PackageParser.Package newPackage = null;
17870        try {
17871            // Add the package to the internal data structures
17872            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17873
17874            // Set the update and install times
17875            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17876            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17877                    System.currentTimeMillis());
17878
17879            // Update the package dynamic state if succeeded
17880            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17881                // Now that the install succeeded make sure we remove data
17882                // directories for any child package the update removed.
17883                final int deletedChildCount = (deletedPackage.childPackages != null)
17884                        ? deletedPackage.childPackages.size() : 0;
17885                final int newChildCount = (newPackage.childPackages != null)
17886                        ? newPackage.childPackages.size() : 0;
17887                for (int i = 0; i < deletedChildCount; i++) {
17888                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17889                    boolean childPackageDeleted = true;
17890                    for (int j = 0; j < newChildCount; j++) {
17891                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17892                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17893                            childPackageDeleted = false;
17894                            break;
17895                        }
17896                    }
17897                    if (childPackageDeleted) {
17898                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17899                                deletedChildPkg.packageName);
17900                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17901                            PackageRemovedInfo removedChildRes = res.removedInfo
17902                                    .removedChildPackages.get(deletedChildPkg.packageName);
17903                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17904                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17905                        }
17906                    }
17907                }
17908
17909                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17910                        installReason);
17911                prepareAppDataAfterInstallLIF(newPackage);
17912
17913                mDexManager.notifyPackageUpdated(newPackage.packageName,
17914                            newPackage.baseCodePath, newPackage.splitCodePaths);
17915            }
17916        } catch (PackageManagerException e) {
17917            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17918            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17919        }
17920
17921        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17922            // Re installation failed. Restore old information
17923            // Remove new pkg information
17924            if (newPackage != null) {
17925                removeInstalledPackageLI(newPackage, true);
17926            }
17927            // Add back the old system package
17928            try {
17929                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17930            } catch (PackageManagerException e) {
17931                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17932            }
17933
17934            synchronized (mPackages) {
17935                if (disabledSystem) {
17936                    enableSystemPackageLPw(deletedPackage);
17937                }
17938
17939                // Ensure the installer package name up to date
17940                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17941
17942                // Update permissions for restored package
17943                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17944
17945                mSettings.writeLPr();
17946            }
17947
17948            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17949                    + " after failed upgrade");
17950        }
17951    }
17952
17953    /**
17954     * Checks whether the parent or any of the child packages have a change shared
17955     * user. For a package to be a valid update the shred users of the parent and
17956     * the children should match. We may later support changing child shared users.
17957     * @param oldPkg The updated package.
17958     * @param newPkg The update package.
17959     * @return The shared user that change between the versions.
17960     */
17961    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17962            PackageParser.Package newPkg) {
17963        // Check parent shared user
17964        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17965            return newPkg.packageName;
17966        }
17967        // Check child shared users
17968        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17969        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17970        for (int i = 0; i < newChildCount; i++) {
17971            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17972            // If this child was present, did it have the same shared user?
17973            for (int j = 0; j < oldChildCount; j++) {
17974                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17975                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17976                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17977                    return newChildPkg.packageName;
17978                }
17979            }
17980        }
17981        return null;
17982    }
17983
17984    private void removeNativeBinariesLI(PackageSetting ps) {
17985        // Remove the lib path for the parent package
17986        if (ps != null) {
17987            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17988            // Remove the lib path for the child packages
17989            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17990            for (int i = 0; i < childCount; i++) {
17991                PackageSetting childPs = null;
17992                synchronized (mPackages) {
17993                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17994                }
17995                if (childPs != null) {
17996                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17997                            .legacyNativeLibraryPathString);
17998                }
17999            }
18000        }
18001    }
18002
18003    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18004        // Enable the parent package
18005        mSettings.enableSystemPackageLPw(pkg.packageName);
18006        // Enable the child packages
18007        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18008        for (int i = 0; i < childCount; i++) {
18009            PackageParser.Package childPkg = pkg.childPackages.get(i);
18010            mSettings.enableSystemPackageLPw(childPkg.packageName);
18011        }
18012    }
18013
18014    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18015            PackageParser.Package newPkg) {
18016        // Disable the parent package (parent always replaced)
18017        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18018        // Disable the child packages
18019        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18020        for (int i = 0; i < childCount; i++) {
18021            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18022            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18023            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18024        }
18025        return disabled;
18026    }
18027
18028    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18029            String installerPackageName) {
18030        // Enable the parent package
18031        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18032        // Enable the child packages
18033        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18034        for (int i = 0; i < childCount; i++) {
18035            PackageParser.Package childPkg = pkg.childPackages.get(i);
18036            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18037        }
18038    }
18039
18040    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18041        // Collect all used permissions in the UID
18042        ArraySet<String> usedPermissions = new ArraySet<>();
18043        final int packageCount = su.packages.size();
18044        for (int i = 0; i < packageCount; i++) {
18045            PackageSetting ps = su.packages.valueAt(i);
18046            if (ps.pkg == null) {
18047                continue;
18048            }
18049            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18050            for (int j = 0; j < requestedPermCount; j++) {
18051                String permission = ps.pkg.requestedPermissions.get(j);
18052                BasePermission bp = mSettings.mPermissions.get(permission);
18053                if (bp != null) {
18054                    usedPermissions.add(permission);
18055                }
18056            }
18057        }
18058
18059        PermissionsState permissionsState = su.getPermissionsState();
18060        // Prune install permissions
18061        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18062        final int installPermCount = installPermStates.size();
18063        for (int i = installPermCount - 1; i >= 0;  i--) {
18064            PermissionState permissionState = installPermStates.get(i);
18065            if (!usedPermissions.contains(permissionState.getName())) {
18066                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18067                if (bp != null) {
18068                    permissionsState.revokeInstallPermission(bp);
18069                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18070                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18071                }
18072            }
18073        }
18074
18075        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18076
18077        // Prune runtime permissions
18078        for (int userId : allUserIds) {
18079            List<PermissionState> runtimePermStates = permissionsState
18080                    .getRuntimePermissionStates(userId);
18081            final int runtimePermCount = runtimePermStates.size();
18082            for (int i = runtimePermCount - 1; i >= 0; i--) {
18083                PermissionState permissionState = runtimePermStates.get(i);
18084                if (!usedPermissions.contains(permissionState.getName())) {
18085                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18086                    if (bp != null) {
18087                        permissionsState.revokeRuntimePermission(bp, userId);
18088                        permissionsState.updatePermissionFlags(bp, userId,
18089                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18090                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18091                                runtimePermissionChangedUserIds, userId);
18092                    }
18093                }
18094            }
18095        }
18096
18097        return runtimePermissionChangedUserIds;
18098    }
18099
18100    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18101            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18102        // Update the parent package setting
18103        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18104                res, user, installReason);
18105        // Update the child packages setting
18106        final int childCount = (newPackage.childPackages != null)
18107                ? newPackage.childPackages.size() : 0;
18108        for (int i = 0; i < childCount; i++) {
18109            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18110            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18111            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18112                    childRes.origUsers, childRes, user, installReason);
18113        }
18114    }
18115
18116    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18117            String installerPackageName, int[] allUsers, int[] installedForUsers,
18118            PackageInstalledInfo res, UserHandle user, int installReason) {
18119        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18120
18121        String pkgName = newPackage.packageName;
18122        synchronized (mPackages) {
18123            //write settings. the installStatus will be incomplete at this stage.
18124            //note that the new package setting would have already been
18125            //added to mPackages. It hasn't been persisted yet.
18126            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18127            // TODO: Remove this write? It's also written at the end of this method
18128            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18129            mSettings.writeLPr();
18130            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18131        }
18132
18133        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18134        synchronized (mPackages) {
18135            updatePermissionsLPw(newPackage.packageName, newPackage,
18136                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18137                            ? UPDATE_PERMISSIONS_ALL : 0));
18138            // For system-bundled packages, we assume that installing an upgraded version
18139            // of the package implies that the user actually wants to run that new code,
18140            // so we enable the package.
18141            PackageSetting ps = mSettings.mPackages.get(pkgName);
18142            final int userId = user.getIdentifier();
18143            if (ps != null) {
18144                if (isSystemApp(newPackage)) {
18145                    if (DEBUG_INSTALL) {
18146                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18147                    }
18148                    // Enable system package for requested users
18149                    if (res.origUsers != null) {
18150                        for (int origUserId : res.origUsers) {
18151                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18152                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18153                                        origUserId, installerPackageName);
18154                            }
18155                        }
18156                    }
18157                    // Also convey the prior install/uninstall state
18158                    if (allUsers != null && installedForUsers != null) {
18159                        for (int currentUserId : allUsers) {
18160                            final boolean installed = ArrayUtils.contains(
18161                                    installedForUsers, currentUserId);
18162                            if (DEBUG_INSTALL) {
18163                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18164                            }
18165                            ps.setInstalled(installed, currentUserId);
18166                        }
18167                        // these install state changes will be persisted in the
18168                        // upcoming call to mSettings.writeLPr().
18169                    }
18170                }
18171                // It's implied that when a user requests installation, they want the app to be
18172                // installed and enabled.
18173                if (userId != UserHandle.USER_ALL) {
18174                    ps.setInstalled(true, userId);
18175                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18176                }
18177
18178                // When replacing an existing package, preserve the original install reason for all
18179                // users that had the package installed before.
18180                final Set<Integer> previousUserIds = new ArraySet<>();
18181                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18182                    final int installReasonCount = res.removedInfo.installReasons.size();
18183                    for (int i = 0; i < installReasonCount; i++) {
18184                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18185                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18186                        ps.setInstallReason(previousInstallReason, previousUserId);
18187                        previousUserIds.add(previousUserId);
18188                    }
18189                }
18190
18191                // Set install reason for users that are having the package newly installed.
18192                if (userId == UserHandle.USER_ALL) {
18193                    for (int currentUserId : sUserManager.getUserIds()) {
18194                        if (!previousUserIds.contains(currentUserId)) {
18195                            ps.setInstallReason(installReason, currentUserId);
18196                        }
18197                    }
18198                } else if (!previousUserIds.contains(userId)) {
18199                    ps.setInstallReason(installReason, userId);
18200                }
18201                mSettings.writeKernelMappingLPr(ps);
18202            }
18203            res.name = pkgName;
18204            res.uid = newPackage.applicationInfo.uid;
18205            res.pkg = newPackage;
18206            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18207            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18208            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18209            //to update install status
18210            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18211            mSettings.writeLPr();
18212            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18213        }
18214
18215        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18216    }
18217
18218    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18219        try {
18220            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18221            installPackageLI(args, res);
18222        } finally {
18223            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18224        }
18225    }
18226
18227    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18228        final int installFlags = args.installFlags;
18229        final String installerPackageName = args.installerPackageName;
18230        final String volumeUuid = args.volumeUuid;
18231        final File tmpPackageFile = new File(args.getCodePath());
18232        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18233        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18234                || (args.volumeUuid != null));
18235        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18236        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18237        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18238        final boolean virtualPreload =
18239                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18240        boolean replace = false;
18241        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18242        if (args.move != null) {
18243            // moving a complete application; perform an initial scan on the new install location
18244            scanFlags |= SCAN_INITIAL;
18245        }
18246        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18247            scanFlags |= SCAN_DONT_KILL_APP;
18248        }
18249        if (instantApp) {
18250            scanFlags |= SCAN_AS_INSTANT_APP;
18251        }
18252        if (fullApp) {
18253            scanFlags |= SCAN_AS_FULL_APP;
18254        }
18255        if (virtualPreload) {
18256            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18257        }
18258
18259        // Result object to be returned
18260        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18261        res.installerPackageName = installerPackageName;
18262
18263        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18264
18265        // Sanity check
18266        if (instantApp && (forwardLocked || onExternal)) {
18267            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18268                    + " external=" + onExternal);
18269            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18270            return;
18271        }
18272
18273        // Retrieve PackageSettings and parse package
18274        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18275                | PackageParser.PARSE_ENFORCE_CODE
18276                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18277                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18278                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18279                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18280        PackageParser pp = new PackageParser();
18281        pp.setSeparateProcesses(mSeparateProcesses);
18282        pp.setDisplayMetrics(mMetrics);
18283        pp.setCallback(mPackageParserCallback);
18284
18285        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18286        final PackageParser.Package pkg;
18287        try {
18288            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18289        } catch (PackageParserException e) {
18290            res.setError("Failed parse during installPackageLI", e);
18291            return;
18292        } finally {
18293            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18294        }
18295
18296        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18297        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18298            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18299            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18300                    "Instant app package must target O");
18301            return;
18302        }
18303        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18304            Slog.w(TAG, "Instant app package " + pkg.packageName
18305                    + " does not target targetSandboxVersion 2");
18306            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18307                    "Instant app package must use targetSanboxVersion 2");
18308            return;
18309        }
18310
18311        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18312            // Static shared libraries have synthetic package names
18313            renameStaticSharedLibraryPackage(pkg);
18314
18315            // No static shared libs on external storage
18316            if (onExternal) {
18317                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18318                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18319                        "Packages declaring static-shared libs cannot be updated");
18320                return;
18321            }
18322        }
18323
18324        // If we are installing a clustered package add results for the children
18325        if (pkg.childPackages != null) {
18326            synchronized (mPackages) {
18327                final int childCount = pkg.childPackages.size();
18328                for (int i = 0; i < childCount; i++) {
18329                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18330                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18331                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18332                    childRes.pkg = childPkg;
18333                    childRes.name = childPkg.packageName;
18334                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18335                    if (childPs != null) {
18336                        childRes.origUsers = childPs.queryInstalledUsers(
18337                                sUserManager.getUserIds(), true);
18338                    }
18339                    if ((mPackages.containsKey(childPkg.packageName))) {
18340                        childRes.removedInfo = new PackageRemovedInfo(this);
18341                        childRes.removedInfo.removedPackage = childPkg.packageName;
18342                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18343                    }
18344                    if (res.addedChildPackages == null) {
18345                        res.addedChildPackages = new ArrayMap<>();
18346                    }
18347                    res.addedChildPackages.put(childPkg.packageName, childRes);
18348                }
18349            }
18350        }
18351
18352        // If package doesn't declare API override, mark that we have an install
18353        // time CPU ABI override.
18354        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18355            pkg.cpuAbiOverride = args.abiOverride;
18356        }
18357
18358        String pkgName = res.name = pkg.packageName;
18359        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18360            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18361                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18362                return;
18363            }
18364        }
18365
18366        try {
18367            // either use what we've been given or parse directly from the APK
18368            if (args.certificates != null) {
18369                try {
18370                    PackageParser.populateCertificates(pkg, args.certificates);
18371                } catch (PackageParserException e) {
18372                    // there was something wrong with the certificates we were given;
18373                    // try to pull them from the APK
18374                    PackageParser.collectCertificates(pkg, parseFlags);
18375                }
18376            } else {
18377                PackageParser.collectCertificates(pkg, parseFlags);
18378            }
18379        } catch (PackageParserException e) {
18380            res.setError("Failed collect during installPackageLI", e);
18381            return;
18382        }
18383
18384        // Get rid of all references to package scan path via parser.
18385        pp = null;
18386        String oldCodePath = null;
18387        boolean systemApp = false;
18388        synchronized (mPackages) {
18389            // Check if installing already existing package
18390            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18391                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18392                if (pkg.mOriginalPackages != null
18393                        && pkg.mOriginalPackages.contains(oldName)
18394                        && mPackages.containsKey(oldName)) {
18395                    // This package is derived from an original package,
18396                    // and this device has been updating from that original
18397                    // name.  We must continue using the original name, so
18398                    // rename the new package here.
18399                    pkg.setPackageName(oldName);
18400                    pkgName = pkg.packageName;
18401                    replace = true;
18402                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18403                            + oldName + " pkgName=" + pkgName);
18404                } else if (mPackages.containsKey(pkgName)) {
18405                    // This package, under its official name, already exists
18406                    // on the device; we should replace it.
18407                    replace = true;
18408                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18409                }
18410
18411                // Child packages are installed through the parent package
18412                if (pkg.parentPackage != null) {
18413                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18414                            "Package " + pkg.packageName + " is child of package "
18415                                    + pkg.parentPackage.parentPackage + ". Child packages "
18416                                    + "can be updated only through the parent package.");
18417                    return;
18418                }
18419
18420                if (replace) {
18421                    // Prevent apps opting out from runtime permissions
18422                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18423                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18424                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18425                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18426                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18427                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18428                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18429                                        + " doesn't support runtime permissions but the old"
18430                                        + " target SDK " + oldTargetSdk + " does.");
18431                        return;
18432                    }
18433                    // Prevent apps from downgrading their targetSandbox.
18434                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18435                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18436                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18437                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18438                                "Package " + pkg.packageName + " new target sandbox "
18439                                + newTargetSandbox + " is incompatible with the previous value of"
18440                                + oldTargetSandbox + ".");
18441                        return;
18442                    }
18443
18444                    // Prevent installing of child packages
18445                    if (oldPackage.parentPackage != null) {
18446                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18447                                "Package " + pkg.packageName + " is child of package "
18448                                        + oldPackage.parentPackage + ". Child packages "
18449                                        + "can be updated only through the parent package.");
18450                        return;
18451                    }
18452                }
18453            }
18454
18455            PackageSetting ps = mSettings.mPackages.get(pkgName);
18456            if (ps != null) {
18457                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18458
18459                // Static shared libs have same package with different versions where
18460                // we internally use a synthetic package name to allow multiple versions
18461                // of the same package, therefore we need to compare signatures against
18462                // the package setting for the latest library version.
18463                PackageSetting signatureCheckPs = ps;
18464                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18465                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18466                    if (libraryEntry != null) {
18467                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18468                    }
18469                }
18470
18471                // Quick sanity check that we're signed correctly if updating;
18472                // we'll check this again later when scanning, but we want to
18473                // bail early here before tripping over redefined permissions.
18474                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18475                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18476                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18477                                + pkg.packageName + " upgrade keys do not match the "
18478                                + "previously installed version");
18479                        return;
18480                    }
18481                } else {
18482                    try {
18483                        verifySignaturesLP(signatureCheckPs, pkg);
18484                    } catch (PackageManagerException e) {
18485                        res.setError(e.error, e.getMessage());
18486                        return;
18487                    }
18488                }
18489
18490                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18491                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18492                    systemApp = (ps.pkg.applicationInfo.flags &
18493                            ApplicationInfo.FLAG_SYSTEM) != 0;
18494                }
18495                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18496            }
18497
18498            int N = pkg.permissions.size();
18499            for (int i = N-1; i >= 0; i--) {
18500                PackageParser.Permission perm = pkg.permissions.get(i);
18501                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18502
18503                // Don't allow anyone but the system to define ephemeral permissions.
18504                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18505                        && !systemApp) {
18506                    Slog.w(TAG, "Non-System package " + pkg.packageName
18507                            + " attempting to delcare ephemeral permission "
18508                            + perm.info.name + "; Removing ephemeral.");
18509                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18510                }
18511
18512                // Check whether the newly-scanned package wants to define an already-defined perm
18513                if (bp != null) {
18514                    // If the defining package is signed with our cert, it's okay.  This
18515                    // also includes the "updating the same package" case, of course.
18516                    // "updating same package" could also involve key-rotation.
18517                    final boolean sigsOk;
18518                    final String sourcePackageName = bp.getSourcePackageName();
18519                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
18520                    if (sourcePackageName.equals(pkg.packageName)
18521                            && (shouldCheckUpgradeKeySetLP(sourcePackageSetting,
18522                                    scanFlags))) {
18523                        sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg);
18524                    } else {
18525                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
18526                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18527                    }
18528                    if (!sigsOk) {
18529                        // If the owning package is the system itself, we log but allow
18530                        // install to proceed; we fail the install on all other permission
18531                        // redefinitions.
18532                        if (!sourcePackageName.equals("android")) {
18533                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18534                                    + pkg.packageName + " attempting to redeclare permission "
18535                                    + perm.info.name + " already owned by " + sourcePackageName);
18536                            res.origPermission = perm.info.name;
18537                            res.origPackage = sourcePackageName;
18538                            return;
18539                        } else {
18540                            Slog.w(TAG, "Package " + pkg.packageName
18541                                    + " attempting to redeclare system permission "
18542                                    + perm.info.name + "; ignoring new declaration");
18543                            pkg.permissions.remove(i);
18544                        }
18545                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18546                        // Prevent apps to change protection level to dangerous from any other
18547                        // type as this would allow a privilege escalation where an app adds a
18548                        // normal/signature permission in other app's group and later redefines
18549                        // it as dangerous leading to the group auto-grant.
18550                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18551                                == PermissionInfo.PROTECTION_DANGEROUS) {
18552                            if (bp != null && !bp.isRuntime()) {
18553                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18554                                        + "non-runtime permission " + perm.info.name
18555                                        + " to runtime; keeping old protection level");
18556                                perm.info.protectionLevel = bp.getProtectionLevel();
18557                            }
18558                        }
18559                    }
18560                }
18561            }
18562        }
18563
18564        if (systemApp) {
18565            if (onExternal) {
18566                // Abort update; system app can't be replaced with app on sdcard
18567                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18568                        "Cannot install updates to system apps on sdcard");
18569                return;
18570            } else if (instantApp) {
18571                // Abort update; system app can't be replaced with an instant app
18572                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18573                        "Cannot update a system app with an instant app");
18574                return;
18575            }
18576        }
18577
18578        if (args.move != null) {
18579            // We did an in-place move, so dex is ready to roll
18580            scanFlags |= SCAN_NO_DEX;
18581            scanFlags |= SCAN_MOVE;
18582
18583            synchronized (mPackages) {
18584                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18585                if (ps == null) {
18586                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18587                            "Missing settings for moved package " + pkgName);
18588                }
18589
18590                // We moved the entire application as-is, so bring over the
18591                // previously derived ABI information.
18592                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18593                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18594            }
18595
18596        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18597            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18598            scanFlags |= SCAN_NO_DEX;
18599
18600            try {
18601                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18602                    args.abiOverride : pkg.cpuAbiOverride);
18603                final boolean extractNativeLibs = !pkg.isLibrary();
18604                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18605                        extractNativeLibs, mAppLib32InstallDir);
18606            } catch (PackageManagerException pme) {
18607                Slog.e(TAG, "Error deriving application ABI", pme);
18608                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18609                return;
18610            }
18611
18612            // Shared libraries for the package need to be updated.
18613            synchronized (mPackages) {
18614                try {
18615                    updateSharedLibrariesLPr(pkg, null);
18616                } catch (PackageManagerException e) {
18617                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18618                }
18619            }
18620        }
18621
18622        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18623            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18624            return;
18625        }
18626
18627        // Verify if we need to dexopt the app.
18628        //
18629        // NOTE: it is *important* to call dexopt after doRename which will sync the
18630        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18631        //
18632        // We only need to dexopt if the package meets ALL of the following conditions:
18633        //   1) it is not forward locked.
18634        //   2) it is not on on an external ASEC container.
18635        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18636        //
18637        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18638        // complete, so we skip this step during installation. Instead, we'll take extra time
18639        // the first time the instant app starts. It's preferred to do it this way to provide
18640        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18641        // middle of running an instant app. The default behaviour can be overridden
18642        // via gservices.
18643        final boolean performDexopt = !forwardLocked
18644            && !pkg.applicationInfo.isExternalAsec()
18645            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18646                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18647
18648        if (performDexopt) {
18649            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18650            // Do not run PackageDexOptimizer through the local performDexOpt
18651            // method because `pkg` may not be in `mPackages` yet.
18652            //
18653            // Also, don't fail application installs if the dexopt step fails.
18654            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18655                REASON_INSTALL,
18656                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18657            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18658                null /* instructionSets */,
18659                getOrCreateCompilerPackageStats(pkg),
18660                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18661                dexoptOptions);
18662            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18663        }
18664
18665        // Notify BackgroundDexOptService that the package has been changed.
18666        // If this is an update of a package which used to fail to compile,
18667        // BackgroundDexOptService will remove it from its blacklist.
18668        // TODO: Layering violation
18669        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18670
18671        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18672
18673        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18674                "installPackageLI")) {
18675            if (replace) {
18676                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18677                    // Static libs have a synthetic package name containing the version
18678                    // and cannot be updated as an update would get a new package name,
18679                    // unless this is the exact same version code which is useful for
18680                    // development.
18681                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18682                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18683                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18684                                + "static-shared libs cannot be updated");
18685                        return;
18686                    }
18687                }
18688                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18689                        installerPackageName, res, args.installReason);
18690            } else {
18691                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18692                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18693            }
18694        }
18695
18696        synchronized (mPackages) {
18697            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18698            if (ps != null) {
18699                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18700                ps.setUpdateAvailable(false /*updateAvailable*/);
18701            }
18702
18703            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18704            for (int i = 0; i < childCount; i++) {
18705                PackageParser.Package childPkg = pkg.childPackages.get(i);
18706                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18707                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18708                if (childPs != null) {
18709                    childRes.newUsers = childPs.queryInstalledUsers(
18710                            sUserManager.getUserIds(), true);
18711                }
18712            }
18713
18714            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18715                updateSequenceNumberLP(ps, res.newUsers);
18716                updateInstantAppInstallerLocked(pkgName);
18717            }
18718        }
18719    }
18720
18721    private void startIntentFilterVerifications(int userId, boolean replacing,
18722            PackageParser.Package pkg) {
18723        if (mIntentFilterVerifierComponent == null) {
18724            Slog.w(TAG, "No IntentFilter verification will not be done as "
18725                    + "there is no IntentFilterVerifier available!");
18726            return;
18727        }
18728
18729        final int verifierUid = getPackageUid(
18730                mIntentFilterVerifierComponent.getPackageName(),
18731                MATCH_DEBUG_TRIAGED_MISSING,
18732                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18733
18734        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18735        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18736        mHandler.sendMessage(msg);
18737
18738        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18739        for (int i = 0; i < childCount; i++) {
18740            PackageParser.Package childPkg = pkg.childPackages.get(i);
18741            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18742            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18743            mHandler.sendMessage(msg);
18744        }
18745    }
18746
18747    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18748            PackageParser.Package pkg) {
18749        int size = pkg.activities.size();
18750        if (size == 0) {
18751            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18752                    "No activity, so no need to verify any IntentFilter!");
18753            return;
18754        }
18755
18756        final boolean hasDomainURLs = hasDomainURLs(pkg);
18757        if (!hasDomainURLs) {
18758            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18759                    "No domain URLs, so no need to verify any IntentFilter!");
18760            return;
18761        }
18762
18763        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18764                + " if any IntentFilter from the " + size
18765                + " Activities needs verification ...");
18766
18767        int count = 0;
18768        final String packageName = pkg.packageName;
18769
18770        synchronized (mPackages) {
18771            // If this is a new install and we see that we've already run verification for this
18772            // package, we have nothing to do: it means the state was restored from backup.
18773            if (!replacing) {
18774                IntentFilterVerificationInfo ivi =
18775                        mSettings.getIntentFilterVerificationLPr(packageName);
18776                if (ivi != null) {
18777                    if (DEBUG_DOMAIN_VERIFICATION) {
18778                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18779                                + ivi.getStatusString());
18780                    }
18781                    return;
18782                }
18783            }
18784
18785            // If any filters need to be verified, then all need to be.
18786            boolean needToVerify = false;
18787            for (PackageParser.Activity a : pkg.activities) {
18788                for (ActivityIntentInfo filter : a.intents) {
18789                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18790                        if (DEBUG_DOMAIN_VERIFICATION) {
18791                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18792                        }
18793                        needToVerify = true;
18794                        break;
18795                    }
18796                }
18797            }
18798
18799            if (needToVerify) {
18800                final int verificationId = mIntentFilterVerificationToken++;
18801                for (PackageParser.Activity a : pkg.activities) {
18802                    for (ActivityIntentInfo filter : a.intents) {
18803                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18804                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18805                                    "Verification needed for IntentFilter:" + filter.toString());
18806                            mIntentFilterVerifier.addOneIntentFilterVerification(
18807                                    verifierUid, userId, verificationId, filter, packageName);
18808                            count++;
18809                        }
18810                    }
18811                }
18812            }
18813        }
18814
18815        if (count > 0) {
18816            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18817                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18818                    +  " for userId:" + userId);
18819            mIntentFilterVerifier.startVerifications(userId);
18820        } else {
18821            if (DEBUG_DOMAIN_VERIFICATION) {
18822                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18823            }
18824        }
18825    }
18826
18827    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18828        final ComponentName cn  = filter.activity.getComponentName();
18829        final String packageName = cn.getPackageName();
18830
18831        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18832                packageName);
18833        if (ivi == null) {
18834            return true;
18835        }
18836        int status = ivi.getStatus();
18837        switch (status) {
18838            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18839            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18840                return true;
18841
18842            default:
18843                // Nothing to do
18844                return false;
18845        }
18846    }
18847
18848    private static boolean isMultiArch(ApplicationInfo info) {
18849        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18850    }
18851
18852    private static boolean isExternal(PackageParser.Package pkg) {
18853        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18854    }
18855
18856    private static boolean isExternal(PackageSetting ps) {
18857        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18858    }
18859
18860    private static boolean isSystemApp(PackageParser.Package pkg) {
18861        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18862    }
18863
18864    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18865        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18866    }
18867
18868    private static boolean isOemApp(PackageParser.Package pkg) {
18869        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
18870    }
18871
18872    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18873        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18874    }
18875
18876    private static boolean isSystemApp(PackageSetting ps) {
18877        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18878    }
18879
18880    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18881        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18882    }
18883
18884    private int packageFlagsToInstallFlags(PackageSetting ps) {
18885        int installFlags = 0;
18886        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18887            // This existing package was an external ASEC install when we have
18888            // the external flag without a UUID
18889            installFlags |= PackageManager.INSTALL_EXTERNAL;
18890        }
18891        if (ps.isForwardLocked()) {
18892            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18893        }
18894        return installFlags;
18895    }
18896
18897    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18898        if (isExternal(pkg)) {
18899            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18900                return StorageManager.UUID_PRIMARY_PHYSICAL;
18901            } else {
18902                return pkg.volumeUuid;
18903            }
18904        } else {
18905            return StorageManager.UUID_PRIVATE_INTERNAL;
18906        }
18907    }
18908
18909    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18910        if (isExternal(pkg)) {
18911            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18912                return mSettings.getExternalVersion();
18913            } else {
18914                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18915            }
18916        } else {
18917            return mSettings.getInternalVersion();
18918        }
18919    }
18920
18921    private void deleteTempPackageFiles() {
18922        final FilenameFilter filter = new FilenameFilter() {
18923            public boolean accept(File dir, String name) {
18924                return name.startsWith("vmdl") && name.endsWith(".tmp");
18925            }
18926        };
18927        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18928            file.delete();
18929        }
18930    }
18931
18932    @Override
18933    public void deletePackageAsUser(String packageName, int versionCode,
18934            IPackageDeleteObserver observer, int userId, int flags) {
18935        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18936                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18937    }
18938
18939    @Override
18940    public void deletePackageVersioned(VersionedPackage versionedPackage,
18941            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18942        final int callingUid = Binder.getCallingUid();
18943        mContext.enforceCallingOrSelfPermission(
18944                android.Manifest.permission.DELETE_PACKAGES, null);
18945        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18946        Preconditions.checkNotNull(versionedPackage);
18947        Preconditions.checkNotNull(observer);
18948        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18949                PackageManager.VERSION_CODE_HIGHEST,
18950                Integer.MAX_VALUE, "versionCode must be >= -1");
18951
18952        final String packageName = versionedPackage.getPackageName();
18953        final int versionCode = versionedPackage.getVersionCode();
18954        final String internalPackageName;
18955        synchronized (mPackages) {
18956            // Normalize package name to handle renamed packages and static libs
18957            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18958                    versionedPackage.getVersionCode());
18959        }
18960
18961        final int uid = Binder.getCallingUid();
18962        if (!isOrphaned(internalPackageName)
18963                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18964            try {
18965                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18966                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18967                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18968                observer.onUserActionRequired(intent);
18969            } catch (RemoteException re) {
18970            }
18971            return;
18972        }
18973        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18974        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18975        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18976            mContext.enforceCallingOrSelfPermission(
18977                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18978                    "deletePackage for user " + userId);
18979        }
18980
18981        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18982            try {
18983                observer.onPackageDeleted(packageName,
18984                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18985            } catch (RemoteException re) {
18986            }
18987            return;
18988        }
18989
18990        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18991            try {
18992                observer.onPackageDeleted(packageName,
18993                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18994            } catch (RemoteException re) {
18995            }
18996            return;
18997        }
18998
18999        if (DEBUG_REMOVE) {
19000            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19001                    + " deleteAllUsers: " + deleteAllUsers + " version="
19002                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19003                    ? "VERSION_CODE_HIGHEST" : versionCode));
19004        }
19005        // Queue up an async operation since the package deletion may take a little while.
19006        mHandler.post(new Runnable() {
19007            public void run() {
19008                mHandler.removeCallbacks(this);
19009                int returnCode;
19010                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19011                boolean doDeletePackage = true;
19012                if (ps != null) {
19013                    final boolean targetIsInstantApp =
19014                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19015                    doDeletePackage = !targetIsInstantApp
19016                            || canViewInstantApps;
19017                }
19018                if (doDeletePackage) {
19019                    if (!deleteAllUsers) {
19020                        returnCode = deletePackageX(internalPackageName, versionCode,
19021                                userId, deleteFlags);
19022                    } else {
19023                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19024                                internalPackageName, users);
19025                        // If nobody is blocking uninstall, proceed with delete for all users
19026                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19027                            returnCode = deletePackageX(internalPackageName, versionCode,
19028                                    userId, deleteFlags);
19029                        } else {
19030                            // Otherwise uninstall individually for users with blockUninstalls=false
19031                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19032                            for (int userId : users) {
19033                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19034                                    returnCode = deletePackageX(internalPackageName, versionCode,
19035                                            userId, userFlags);
19036                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19037                                        Slog.w(TAG, "Package delete failed for user " + userId
19038                                                + ", returnCode " + returnCode);
19039                                    }
19040                                }
19041                            }
19042                            // The app has only been marked uninstalled for certain users.
19043                            // We still need to report that delete was blocked
19044                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19045                        }
19046                    }
19047                } else {
19048                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19049                }
19050                try {
19051                    observer.onPackageDeleted(packageName, returnCode, null);
19052                } catch (RemoteException e) {
19053                    Log.i(TAG, "Observer no longer exists.");
19054                } //end catch
19055            } //end run
19056        });
19057    }
19058
19059    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19060        if (pkg.staticSharedLibName != null) {
19061            return pkg.manifestPackageName;
19062        }
19063        return pkg.packageName;
19064    }
19065
19066    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19067        // Handle renamed packages
19068        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19069        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19070
19071        // Is this a static library?
19072        SparseArray<SharedLibraryEntry> versionedLib =
19073                mStaticLibsByDeclaringPackage.get(packageName);
19074        if (versionedLib == null || versionedLib.size() <= 0) {
19075            return packageName;
19076        }
19077
19078        // Figure out which lib versions the caller can see
19079        SparseIntArray versionsCallerCanSee = null;
19080        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19081        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19082                && callingAppId != Process.ROOT_UID) {
19083            versionsCallerCanSee = new SparseIntArray();
19084            String libName = versionedLib.valueAt(0).info.getName();
19085            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19086            if (uidPackages != null) {
19087                for (String uidPackage : uidPackages) {
19088                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19089                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19090                    if (libIdx >= 0) {
19091                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19092                        versionsCallerCanSee.append(libVersion, libVersion);
19093                    }
19094                }
19095            }
19096        }
19097
19098        // Caller can see nothing - done
19099        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19100            return packageName;
19101        }
19102
19103        // Find the version the caller can see and the app version code
19104        SharedLibraryEntry highestVersion = null;
19105        final int versionCount = versionedLib.size();
19106        for (int i = 0; i < versionCount; i++) {
19107            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19108            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19109                    libEntry.info.getVersion()) < 0) {
19110                continue;
19111            }
19112            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19113            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19114                if (libVersionCode == versionCode) {
19115                    return libEntry.apk;
19116                }
19117            } else if (highestVersion == null) {
19118                highestVersion = libEntry;
19119            } else if (libVersionCode  > highestVersion.info
19120                    .getDeclaringPackage().getVersionCode()) {
19121                highestVersion = libEntry;
19122            }
19123        }
19124
19125        if (highestVersion != null) {
19126            return highestVersion.apk;
19127        }
19128
19129        return packageName;
19130    }
19131
19132    boolean isCallerVerifier(int callingUid) {
19133        final int callingUserId = UserHandle.getUserId(callingUid);
19134        return mRequiredVerifierPackage != null &&
19135                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19136    }
19137
19138    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19139        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19140              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19141            return true;
19142        }
19143        final int callingUserId = UserHandle.getUserId(callingUid);
19144        // If the caller installed the pkgName, then allow it to silently uninstall.
19145        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19146            return true;
19147        }
19148
19149        // Allow package verifier to silently uninstall.
19150        if (mRequiredVerifierPackage != null &&
19151                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19152            return true;
19153        }
19154
19155        // Allow package uninstaller to silently uninstall.
19156        if (mRequiredUninstallerPackage != null &&
19157                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19158            return true;
19159        }
19160
19161        // Allow storage manager to silently uninstall.
19162        if (mStorageManagerPackage != null &&
19163                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19164            return true;
19165        }
19166
19167        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19168        // uninstall for device owner provisioning.
19169        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19170                == PERMISSION_GRANTED) {
19171            return true;
19172        }
19173
19174        return false;
19175    }
19176
19177    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19178        int[] result = EMPTY_INT_ARRAY;
19179        for (int userId : userIds) {
19180            if (getBlockUninstallForUser(packageName, userId)) {
19181                result = ArrayUtils.appendInt(result, userId);
19182            }
19183        }
19184        return result;
19185    }
19186
19187    @Override
19188    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19189        final int callingUid = Binder.getCallingUid();
19190        if (getInstantAppPackageName(callingUid) != null
19191                && !isCallerSameApp(packageName, callingUid)) {
19192            return false;
19193        }
19194        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19195    }
19196
19197    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19198        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19199                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19200        try {
19201            if (dpm != null) {
19202                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19203                        /* callingUserOnly =*/ false);
19204                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19205                        : deviceOwnerComponentName.getPackageName();
19206                // Does the package contains the device owner?
19207                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19208                // this check is probably not needed, since DO should be registered as a device
19209                // admin on some user too. (Original bug for this: b/17657954)
19210                if (packageName.equals(deviceOwnerPackageName)) {
19211                    return true;
19212                }
19213                // Does it contain a device admin for any user?
19214                int[] users;
19215                if (userId == UserHandle.USER_ALL) {
19216                    users = sUserManager.getUserIds();
19217                } else {
19218                    users = new int[]{userId};
19219                }
19220                for (int i = 0; i < users.length; ++i) {
19221                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19222                        return true;
19223                    }
19224                }
19225            }
19226        } catch (RemoteException e) {
19227        }
19228        return false;
19229    }
19230
19231    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19232        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19233    }
19234
19235    /**
19236     *  This method is an internal method that could be get invoked either
19237     *  to delete an installed package or to clean up a failed installation.
19238     *  After deleting an installed package, a broadcast is sent to notify any
19239     *  listeners that the package has been removed. For cleaning up a failed
19240     *  installation, the broadcast is not necessary since the package's
19241     *  installation wouldn't have sent the initial broadcast either
19242     *  The key steps in deleting a package are
19243     *  deleting the package information in internal structures like mPackages,
19244     *  deleting the packages base directories through installd
19245     *  updating mSettings to reflect current status
19246     *  persisting settings for later use
19247     *  sending a broadcast if necessary
19248     */
19249    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19250        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19251        final boolean res;
19252
19253        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19254                ? UserHandle.USER_ALL : userId;
19255
19256        if (isPackageDeviceAdmin(packageName, removeUser)) {
19257            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19258            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19259        }
19260
19261        PackageSetting uninstalledPs = null;
19262        PackageParser.Package pkg = null;
19263
19264        // for the uninstall-updates case and restricted profiles, remember the per-
19265        // user handle installed state
19266        int[] allUsers;
19267        synchronized (mPackages) {
19268            uninstalledPs = mSettings.mPackages.get(packageName);
19269            if (uninstalledPs == null) {
19270                Slog.w(TAG, "Not removing non-existent package " + packageName);
19271                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19272            }
19273
19274            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19275                    && uninstalledPs.versionCode != versionCode) {
19276                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19277                        + uninstalledPs.versionCode + " != " + versionCode);
19278                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19279            }
19280
19281            // Static shared libs can be declared by any package, so let us not
19282            // allow removing a package if it provides a lib others depend on.
19283            pkg = mPackages.get(packageName);
19284
19285            allUsers = sUserManager.getUserIds();
19286
19287            if (pkg != null && pkg.staticSharedLibName != null) {
19288                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19289                        pkg.staticSharedLibVersion);
19290                if (libEntry != null) {
19291                    for (int currUserId : allUsers) {
19292                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19293                            continue;
19294                        }
19295                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19296                                libEntry.info, 0, currUserId);
19297                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19298                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19299                                    + " hosting lib " + libEntry.info.getName() + " version "
19300                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19301                                    + " for user " + currUserId);
19302                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19303                        }
19304                    }
19305                }
19306            }
19307
19308            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19309        }
19310
19311        final int freezeUser;
19312        if (isUpdatedSystemApp(uninstalledPs)
19313                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19314            // We're downgrading a system app, which will apply to all users, so
19315            // freeze them all during the downgrade
19316            freezeUser = UserHandle.USER_ALL;
19317        } else {
19318            freezeUser = removeUser;
19319        }
19320
19321        synchronized (mInstallLock) {
19322            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19323            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19324                    deleteFlags, "deletePackageX")) {
19325                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19326                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19327            }
19328            synchronized (mPackages) {
19329                if (res) {
19330                    if (pkg != null) {
19331                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19332                    }
19333                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19334                    updateInstantAppInstallerLocked(packageName);
19335                }
19336            }
19337        }
19338
19339        if (res) {
19340            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19341            info.sendPackageRemovedBroadcasts(killApp);
19342            info.sendSystemPackageUpdatedBroadcasts();
19343            info.sendSystemPackageAppearedBroadcasts();
19344        }
19345        // Force a gc here.
19346        Runtime.getRuntime().gc();
19347        // Delete the resources here after sending the broadcast to let
19348        // other processes clean up before deleting resources.
19349        if (info.args != null) {
19350            synchronized (mInstallLock) {
19351                info.args.doPostDeleteLI(true);
19352            }
19353        }
19354
19355        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19356    }
19357
19358    static class PackageRemovedInfo {
19359        final PackageSender packageSender;
19360        String removedPackage;
19361        String installerPackageName;
19362        int uid = -1;
19363        int removedAppId = -1;
19364        int[] origUsers;
19365        int[] removedUsers = null;
19366        int[] broadcastUsers = null;
19367        SparseArray<Integer> installReasons;
19368        boolean isRemovedPackageSystemUpdate = false;
19369        boolean isUpdate;
19370        boolean dataRemoved;
19371        boolean removedForAllUsers;
19372        boolean isStaticSharedLib;
19373        // Clean up resources deleted packages.
19374        InstallArgs args = null;
19375        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19376        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19377
19378        PackageRemovedInfo(PackageSender packageSender) {
19379            this.packageSender = packageSender;
19380        }
19381
19382        void sendPackageRemovedBroadcasts(boolean killApp) {
19383            sendPackageRemovedBroadcastInternal(killApp);
19384            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19385            for (int i = 0; i < childCount; i++) {
19386                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19387                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19388            }
19389        }
19390
19391        void sendSystemPackageUpdatedBroadcasts() {
19392            if (isRemovedPackageSystemUpdate) {
19393                sendSystemPackageUpdatedBroadcastsInternal();
19394                final int childCount = (removedChildPackages != null)
19395                        ? removedChildPackages.size() : 0;
19396                for (int i = 0; i < childCount; i++) {
19397                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19398                    if (childInfo.isRemovedPackageSystemUpdate) {
19399                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19400                    }
19401                }
19402            }
19403        }
19404
19405        void sendSystemPackageAppearedBroadcasts() {
19406            final int packageCount = (appearedChildPackages != null)
19407                    ? appearedChildPackages.size() : 0;
19408            for (int i = 0; i < packageCount; i++) {
19409                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19410                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19411                    true /*sendBootCompleted*/, false /*startReceiver*/,
19412                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19413            }
19414        }
19415
19416        private void sendSystemPackageUpdatedBroadcastsInternal() {
19417            Bundle extras = new Bundle(2);
19418            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19419            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19420            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19421                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19422            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19423                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19424            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19425                null, null, 0, removedPackage, null, null);
19426            if (installerPackageName != null) {
19427                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19428                        removedPackage, extras, 0 /*flags*/,
19429                        installerPackageName, null, null);
19430                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19431                        removedPackage, extras, 0 /*flags*/,
19432                        installerPackageName, null, null);
19433            }
19434        }
19435
19436        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19437            // Don't send static shared library removal broadcasts as these
19438            // libs are visible only the the apps that depend on them an one
19439            // cannot remove the library if it has a dependency.
19440            if (isStaticSharedLib) {
19441                return;
19442            }
19443            Bundle extras = new Bundle(2);
19444            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19445            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19446            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19447            if (isUpdate || isRemovedPackageSystemUpdate) {
19448                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19449            }
19450            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19451            if (removedPackage != null) {
19452                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19453                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19454                if (installerPackageName != null) {
19455                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19456                            removedPackage, extras, 0 /*flags*/,
19457                            installerPackageName, null, broadcastUsers);
19458                }
19459                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19460                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19461                        removedPackage, extras,
19462                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19463                        null, null, broadcastUsers);
19464                }
19465            }
19466            if (removedAppId >= 0) {
19467                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19468                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19469                    null, null, broadcastUsers);
19470            }
19471        }
19472
19473        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19474            removedUsers = userIds;
19475            if (removedUsers == null) {
19476                broadcastUsers = null;
19477                return;
19478            }
19479
19480            broadcastUsers = EMPTY_INT_ARRAY;
19481            for (int i = userIds.length - 1; i >= 0; --i) {
19482                final int userId = userIds[i];
19483                if (deletedPackageSetting.getInstantApp(userId)) {
19484                    continue;
19485                }
19486                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19487            }
19488        }
19489    }
19490
19491    /*
19492     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19493     * flag is not set, the data directory is removed as well.
19494     * make sure this flag is set for partially installed apps. If not its meaningless to
19495     * delete a partially installed application.
19496     */
19497    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19498            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19499        String packageName = ps.name;
19500        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19501        // Retrieve object to delete permissions for shared user later on
19502        final PackageParser.Package deletedPkg;
19503        final PackageSetting deletedPs;
19504        // reader
19505        synchronized (mPackages) {
19506            deletedPkg = mPackages.get(packageName);
19507            deletedPs = mSettings.mPackages.get(packageName);
19508            if (outInfo != null) {
19509                outInfo.removedPackage = packageName;
19510                outInfo.installerPackageName = ps.installerPackageName;
19511                outInfo.isStaticSharedLib = deletedPkg != null
19512                        && deletedPkg.staticSharedLibName != null;
19513                outInfo.populateUsers(deletedPs == null ? null
19514                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19515            }
19516        }
19517
19518        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19519
19520        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19521            final PackageParser.Package resolvedPkg;
19522            if (deletedPkg != null) {
19523                resolvedPkg = deletedPkg;
19524            } else {
19525                // We don't have a parsed package when it lives on an ejected
19526                // adopted storage device, so fake something together
19527                resolvedPkg = new PackageParser.Package(ps.name);
19528                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19529            }
19530            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19531                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19532            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19533            if (outInfo != null) {
19534                outInfo.dataRemoved = true;
19535            }
19536            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19537        }
19538
19539        int removedAppId = -1;
19540
19541        // writer
19542        synchronized (mPackages) {
19543            boolean installedStateChanged = false;
19544            if (deletedPs != null) {
19545                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19546                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19547                    clearDefaultBrowserIfNeeded(packageName);
19548                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19549                    removedAppId = mSettings.removePackageLPw(packageName);
19550                    if (outInfo != null) {
19551                        outInfo.removedAppId = removedAppId;
19552                    }
19553                    updatePermissionsLPw(deletedPs.name, null, 0);
19554                    if (deletedPs.sharedUser != null) {
19555                        // Remove permissions associated with package. Since runtime
19556                        // permissions are per user we have to kill the removed package
19557                        // or packages running under the shared user of the removed
19558                        // package if revoking the permissions requested only by the removed
19559                        // package is successful and this causes a change in gids.
19560                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19561                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19562                                    userId);
19563                            if (userIdToKill == UserHandle.USER_ALL
19564                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19565                                // If gids changed for this user, kill all affected packages.
19566                                mHandler.post(new Runnable() {
19567                                    @Override
19568                                    public void run() {
19569                                        // This has to happen with no lock held.
19570                                        killApplication(deletedPs.name, deletedPs.appId,
19571                                                KILL_APP_REASON_GIDS_CHANGED);
19572                                    }
19573                                });
19574                                break;
19575                            }
19576                        }
19577                    }
19578                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19579                }
19580                // make sure to preserve per-user disabled state if this removal was just
19581                // a downgrade of a system app to the factory package
19582                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19583                    if (DEBUG_REMOVE) {
19584                        Slog.d(TAG, "Propagating install state across downgrade");
19585                    }
19586                    for (int userId : allUserHandles) {
19587                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19588                        if (DEBUG_REMOVE) {
19589                            Slog.d(TAG, "    user " + userId + " => " + installed);
19590                        }
19591                        if (installed != ps.getInstalled(userId)) {
19592                            installedStateChanged = true;
19593                        }
19594                        ps.setInstalled(installed, userId);
19595                    }
19596                }
19597            }
19598            // can downgrade to reader
19599            if (writeSettings) {
19600                // Save settings now
19601                mSettings.writeLPr();
19602            }
19603            if (installedStateChanged) {
19604                mSettings.writeKernelMappingLPr(ps);
19605            }
19606        }
19607        if (removedAppId != -1) {
19608            // A user ID was deleted here. Go through all users and remove it
19609            // from KeyStore.
19610            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19611        }
19612    }
19613
19614    static boolean locationIsPrivileged(File path) {
19615        try {
19616            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19617                    .getCanonicalPath();
19618            return path.getCanonicalPath().startsWith(privilegedAppDir);
19619        } catch (IOException e) {
19620            Slog.e(TAG, "Unable to access code path " + path);
19621        }
19622        return false;
19623    }
19624
19625    static boolean locationIsOem(File path) {
19626        try {
19627            return path.getCanonicalPath().startsWith(
19628                    Environment.getOemDirectory().getCanonicalPath());
19629        } catch (IOException e) {
19630            Slog.e(TAG, "Unable to access code path " + path);
19631        }
19632        return false;
19633    }
19634
19635    /*
19636     * Tries to delete system package.
19637     */
19638    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19639            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19640            boolean writeSettings) {
19641        if (deletedPs.parentPackageName != null) {
19642            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19643            return false;
19644        }
19645
19646        final boolean applyUserRestrictions
19647                = (allUserHandles != null) && (outInfo.origUsers != null);
19648        final PackageSetting disabledPs;
19649        // Confirm if the system package has been updated
19650        // An updated system app can be deleted. This will also have to restore
19651        // the system pkg from system partition
19652        // reader
19653        synchronized (mPackages) {
19654            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19655        }
19656
19657        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19658                + " disabledPs=" + disabledPs);
19659
19660        if (disabledPs == null) {
19661            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19662            return false;
19663        } else if (DEBUG_REMOVE) {
19664            Slog.d(TAG, "Deleting system pkg from data partition");
19665        }
19666
19667        if (DEBUG_REMOVE) {
19668            if (applyUserRestrictions) {
19669                Slog.d(TAG, "Remembering install states:");
19670                for (int userId : allUserHandles) {
19671                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19672                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19673                }
19674            }
19675        }
19676
19677        // Delete the updated package
19678        outInfo.isRemovedPackageSystemUpdate = true;
19679        if (outInfo.removedChildPackages != null) {
19680            final int childCount = (deletedPs.childPackageNames != null)
19681                    ? deletedPs.childPackageNames.size() : 0;
19682            for (int i = 0; i < childCount; i++) {
19683                String childPackageName = deletedPs.childPackageNames.get(i);
19684                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19685                        .contains(childPackageName)) {
19686                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19687                            childPackageName);
19688                    if (childInfo != null) {
19689                        childInfo.isRemovedPackageSystemUpdate = true;
19690                    }
19691                }
19692            }
19693        }
19694
19695        if (disabledPs.versionCode < deletedPs.versionCode) {
19696            // Delete data for downgrades
19697            flags &= ~PackageManager.DELETE_KEEP_DATA;
19698        } else {
19699            // Preserve data by setting flag
19700            flags |= PackageManager.DELETE_KEEP_DATA;
19701        }
19702
19703        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19704                outInfo, writeSettings, disabledPs.pkg);
19705        if (!ret) {
19706            return false;
19707        }
19708
19709        // writer
19710        synchronized (mPackages) {
19711            // NOTE: The system package always needs to be enabled; even if it's for
19712            // a compressed stub. If we don't, installing the system package fails
19713            // during scan [scanning checks the disabled packages]. We will reverse
19714            // this later, after we've "installed" the stub.
19715            // Reinstate the old system package
19716            enableSystemPackageLPw(disabledPs.pkg);
19717            // Remove any native libraries from the upgraded package.
19718            removeNativeBinariesLI(deletedPs);
19719        }
19720
19721        // Install the system package
19722        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19723        try {
19724            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19725                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19726        } catch (PackageManagerException e) {
19727            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19728                    + e.getMessage());
19729            return false;
19730        } finally {
19731            if (disabledPs.pkg.isStub) {
19732                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19733            }
19734        }
19735        return true;
19736    }
19737
19738    /**
19739     * Installs a package that's already on the system partition.
19740     */
19741    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19742            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19743            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19744                    throws PackageManagerException {
19745        int parseFlags = mDefParseFlags
19746                | PackageParser.PARSE_MUST_BE_APK
19747                | PackageParser.PARSE_IS_SYSTEM
19748                | PackageParser.PARSE_IS_SYSTEM_DIR;
19749        if (isPrivileged || locationIsPrivileged(codePath)) {
19750            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19751        }
19752        if (locationIsOem(codePath)) {
19753            parseFlags |= PackageParser.PARSE_IS_OEM;
19754        }
19755
19756        final PackageParser.Package newPkg =
19757                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19758
19759        try {
19760            // update shared libraries for the newly re-installed system package
19761            updateSharedLibrariesLPr(newPkg, null);
19762        } catch (PackageManagerException e) {
19763            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19764        }
19765
19766        prepareAppDataAfterInstallLIF(newPkg);
19767
19768        // writer
19769        synchronized (mPackages) {
19770            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19771
19772            // Propagate the permissions state as we do not want to drop on the floor
19773            // runtime permissions. The update permissions method below will take
19774            // care of removing obsolete permissions and grant install permissions.
19775            if (origPermissionState != null) {
19776                ps.getPermissionsState().copyFrom(origPermissionState);
19777            }
19778            updatePermissionsLPw(newPkg.packageName, newPkg,
19779                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19780
19781            final boolean applyUserRestrictions
19782                    = (allUserHandles != null) && (origUserHandles != null);
19783            if (applyUserRestrictions) {
19784                boolean installedStateChanged = false;
19785                if (DEBUG_REMOVE) {
19786                    Slog.d(TAG, "Propagating install state across reinstall");
19787                }
19788                for (int userId : allUserHandles) {
19789                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19790                    if (DEBUG_REMOVE) {
19791                        Slog.d(TAG, "    user " + userId + " => " + installed);
19792                    }
19793                    if (installed != ps.getInstalled(userId)) {
19794                        installedStateChanged = true;
19795                    }
19796                    ps.setInstalled(installed, userId);
19797
19798                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19799                }
19800                // Regardless of writeSettings we need to ensure that this restriction
19801                // state propagation is persisted
19802                mSettings.writeAllUsersPackageRestrictionsLPr();
19803                if (installedStateChanged) {
19804                    mSettings.writeKernelMappingLPr(ps);
19805                }
19806            }
19807            // can downgrade to reader here
19808            if (writeSettings) {
19809                mSettings.writeLPr();
19810            }
19811        }
19812        return newPkg;
19813    }
19814
19815    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19816            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19817            PackageRemovedInfo outInfo, boolean writeSettings,
19818            PackageParser.Package replacingPackage) {
19819        synchronized (mPackages) {
19820            if (outInfo != null) {
19821                outInfo.uid = ps.appId;
19822            }
19823
19824            if (outInfo != null && outInfo.removedChildPackages != null) {
19825                final int childCount = (ps.childPackageNames != null)
19826                        ? ps.childPackageNames.size() : 0;
19827                for (int i = 0; i < childCount; i++) {
19828                    String childPackageName = ps.childPackageNames.get(i);
19829                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19830                    if (childPs == null) {
19831                        return false;
19832                    }
19833                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19834                            childPackageName);
19835                    if (childInfo != null) {
19836                        childInfo.uid = childPs.appId;
19837                    }
19838                }
19839            }
19840        }
19841
19842        // Delete package data from internal structures and also remove data if flag is set
19843        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19844
19845        // Delete the child packages data
19846        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19847        for (int i = 0; i < childCount; i++) {
19848            PackageSetting childPs;
19849            synchronized (mPackages) {
19850                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19851            }
19852            if (childPs != null) {
19853                PackageRemovedInfo childOutInfo = (outInfo != null
19854                        && outInfo.removedChildPackages != null)
19855                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19856                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19857                        && (replacingPackage != null
19858                        && !replacingPackage.hasChildPackage(childPs.name))
19859                        ? flags & ~DELETE_KEEP_DATA : flags;
19860                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19861                        deleteFlags, writeSettings);
19862            }
19863        }
19864
19865        // Delete application code and resources only for parent packages
19866        if (ps.parentPackageName == null) {
19867            if (deleteCodeAndResources && (outInfo != null)) {
19868                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19869                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19870                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19871            }
19872        }
19873
19874        return true;
19875    }
19876
19877    @Override
19878    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19879            int userId) {
19880        mContext.enforceCallingOrSelfPermission(
19881                android.Manifest.permission.DELETE_PACKAGES, null);
19882        synchronized (mPackages) {
19883            // Cannot block uninstall of static shared libs as they are
19884            // considered a part of the using app (emulating static linking).
19885            // Also static libs are installed always on internal storage.
19886            PackageParser.Package pkg = mPackages.get(packageName);
19887            if (pkg != null && pkg.staticSharedLibName != null) {
19888                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19889                        + " providing static shared library: " + pkg.staticSharedLibName);
19890                return false;
19891            }
19892            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19893            mSettings.writePackageRestrictionsLPr(userId);
19894        }
19895        return true;
19896    }
19897
19898    @Override
19899    public boolean getBlockUninstallForUser(String packageName, int userId) {
19900        synchronized (mPackages) {
19901            final PackageSetting ps = mSettings.mPackages.get(packageName);
19902            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19903                return false;
19904            }
19905            return mSettings.getBlockUninstallLPr(userId, packageName);
19906        }
19907    }
19908
19909    @Override
19910    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19911        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19912        synchronized (mPackages) {
19913            PackageSetting ps = mSettings.mPackages.get(packageName);
19914            if (ps == null) {
19915                Log.w(TAG, "Package doesn't exist: " + packageName);
19916                return false;
19917            }
19918            if (systemUserApp) {
19919                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19920            } else {
19921                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19922            }
19923            mSettings.writeLPr();
19924        }
19925        return true;
19926    }
19927
19928    /*
19929     * This method handles package deletion in general
19930     */
19931    private boolean deletePackageLIF(String packageName, UserHandle user,
19932            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19933            PackageRemovedInfo outInfo, boolean writeSettings,
19934            PackageParser.Package replacingPackage) {
19935        if (packageName == null) {
19936            Slog.w(TAG, "Attempt to delete null packageName.");
19937            return false;
19938        }
19939
19940        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19941
19942        PackageSetting ps;
19943        synchronized (mPackages) {
19944            ps = mSettings.mPackages.get(packageName);
19945            if (ps == null) {
19946                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19947                return false;
19948            }
19949
19950            if (ps.parentPackageName != null && (!isSystemApp(ps)
19951                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19952                if (DEBUG_REMOVE) {
19953                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19954                            + ((user == null) ? UserHandle.USER_ALL : user));
19955                }
19956                final int removedUserId = (user != null) ? user.getIdentifier()
19957                        : UserHandle.USER_ALL;
19958                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19959                    return false;
19960                }
19961                markPackageUninstalledForUserLPw(ps, user);
19962                scheduleWritePackageRestrictionsLocked(user);
19963                return true;
19964            }
19965        }
19966
19967        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19968                && user.getIdentifier() != UserHandle.USER_ALL)) {
19969            // The caller is asking that the package only be deleted for a single
19970            // user.  To do this, we just mark its uninstalled state and delete
19971            // its data. If this is a system app, we only allow this to happen if
19972            // they have set the special DELETE_SYSTEM_APP which requests different
19973            // semantics than normal for uninstalling system apps.
19974            markPackageUninstalledForUserLPw(ps, user);
19975
19976            if (!isSystemApp(ps)) {
19977                // Do not uninstall the APK if an app should be cached
19978                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19979                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19980                    // Other user still have this package installed, so all
19981                    // we need to do is clear this user's data and save that
19982                    // it is uninstalled.
19983                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19984                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19985                        return false;
19986                    }
19987                    scheduleWritePackageRestrictionsLocked(user);
19988                    return true;
19989                } else {
19990                    // We need to set it back to 'installed' so the uninstall
19991                    // broadcasts will be sent correctly.
19992                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19993                    ps.setInstalled(true, user.getIdentifier());
19994                    mSettings.writeKernelMappingLPr(ps);
19995                }
19996            } else {
19997                // This is a system app, so we assume that the
19998                // other users still have this package installed, so all
19999                // we need to do is clear this user's data and save that
20000                // it is uninstalled.
20001                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20002                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20003                    return false;
20004                }
20005                scheduleWritePackageRestrictionsLocked(user);
20006                return true;
20007            }
20008        }
20009
20010        // If we are deleting a composite package for all users, keep track
20011        // of result for each child.
20012        if (ps.childPackageNames != null && outInfo != null) {
20013            synchronized (mPackages) {
20014                final int childCount = ps.childPackageNames.size();
20015                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20016                for (int i = 0; i < childCount; i++) {
20017                    String childPackageName = ps.childPackageNames.get(i);
20018                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20019                    childInfo.removedPackage = childPackageName;
20020                    childInfo.installerPackageName = ps.installerPackageName;
20021                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20022                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20023                    if (childPs != null) {
20024                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20025                    }
20026                }
20027            }
20028        }
20029
20030        boolean ret = false;
20031        if (isSystemApp(ps)) {
20032            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20033            // When an updated system application is deleted we delete the existing resources
20034            // as well and fall back to existing code in system partition
20035            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20036        } else {
20037            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20038            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20039                    outInfo, writeSettings, replacingPackage);
20040        }
20041
20042        // Take a note whether we deleted the package for all users
20043        if (outInfo != null) {
20044            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20045            if (outInfo.removedChildPackages != null) {
20046                synchronized (mPackages) {
20047                    final int childCount = outInfo.removedChildPackages.size();
20048                    for (int i = 0; i < childCount; i++) {
20049                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20050                        if (childInfo != null) {
20051                            childInfo.removedForAllUsers = mPackages.get(
20052                                    childInfo.removedPackage) == null;
20053                        }
20054                    }
20055                }
20056            }
20057            // If we uninstalled an update to a system app there may be some
20058            // child packages that appeared as they are declared in the system
20059            // app but were not declared in the update.
20060            if (isSystemApp(ps)) {
20061                synchronized (mPackages) {
20062                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20063                    final int childCount = (updatedPs.childPackageNames != null)
20064                            ? updatedPs.childPackageNames.size() : 0;
20065                    for (int i = 0; i < childCount; i++) {
20066                        String childPackageName = updatedPs.childPackageNames.get(i);
20067                        if (outInfo.removedChildPackages == null
20068                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20069                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20070                            if (childPs == null) {
20071                                continue;
20072                            }
20073                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20074                            installRes.name = childPackageName;
20075                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20076                            installRes.pkg = mPackages.get(childPackageName);
20077                            installRes.uid = childPs.pkg.applicationInfo.uid;
20078                            if (outInfo.appearedChildPackages == null) {
20079                                outInfo.appearedChildPackages = new ArrayMap<>();
20080                            }
20081                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20082                        }
20083                    }
20084                }
20085            }
20086        }
20087
20088        return ret;
20089    }
20090
20091    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20092        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20093                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20094        for (int nextUserId : userIds) {
20095            if (DEBUG_REMOVE) {
20096                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20097            }
20098            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20099                    false /*installed*/,
20100                    true /*stopped*/,
20101                    true /*notLaunched*/,
20102                    false /*hidden*/,
20103                    false /*suspended*/,
20104                    false /*instantApp*/,
20105                    false /*virtualPreload*/,
20106                    null /*lastDisableAppCaller*/,
20107                    null /*enabledComponents*/,
20108                    null /*disabledComponents*/,
20109                    ps.readUserState(nextUserId).domainVerificationStatus,
20110                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20111        }
20112        mSettings.writeKernelMappingLPr(ps);
20113    }
20114
20115    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20116            PackageRemovedInfo outInfo) {
20117        final PackageParser.Package pkg;
20118        synchronized (mPackages) {
20119            pkg = mPackages.get(ps.name);
20120        }
20121
20122        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20123                : new int[] {userId};
20124        for (int nextUserId : userIds) {
20125            if (DEBUG_REMOVE) {
20126                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20127                        + nextUserId);
20128            }
20129
20130            destroyAppDataLIF(pkg, userId,
20131                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20132            destroyAppProfilesLIF(pkg, userId);
20133            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20134            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20135            schedulePackageCleaning(ps.name, nextUserId, false);
20136            synchronized (mPackages) {
20137                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20138                    scheduleWritePackageRestrictionsLocked(nextUserId);
20139                }
20140                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20141            }
20142        }
20143
20144        if (outInfo != null) {
20145            outInfo.removedPackage = ps.name;
20146            outInfo.installerPackageName = ps.installerPackageName;
20147            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20148            outInfo.removedAppId = ps.appId;
20149            outInfo.removedUsers = userIds;
20150            outInfo.broadcastUsers = userIds;
20151        }
20152
20153        return true;
20154    }
20155
20156    private final class ClearStorageConnection implements ServiceConnection {
20157        IMediaContainerService mContainerService;
20158
20159        @Override
20160        public void onServiceConnected(ComponentName name, IBinder service) {
20161            synchronized (this) {
20162                mContainerService = IMediaContainerService.Stub
20163                        .asInterface(Binder.allowBlocking(service));
20164                notifyAll();
20165            }
20166        }
20167
20168        @Override
20169        public void onServiceDisconnected(ComponentName name) {
20170        }
20171    }
20172
20173    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20174        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20175
20176        final boolean mounted;
20177        if (Environment.isExternalStorageEmulated()) {
20178            mounted = true;
20179        } else {
20180            final String status = Environment.getExternalStorageState();
20181
20182            mounted = status.equals(Environment.MEDIA_MOUNTED)
20183                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20184        }
20185
20186        if (!mounted) {
20187            return;
20188        }
20189
20190        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20191        int[] users;
20192        if (userId == UserHandle.USER_ALL) {
20193            users = sUserManager.getUserIds();
20194        } else {
20195            users = new int[] { userId };
20196        }
20197        final ClearStorageConnection conn = new ClearStorageConnection();
20198        if (mContext.bindServiceAsUser(
20199                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20200            try {
20201                for (int curUser : users) {
20202                    long timeout = SystemClock.uptimeMillis() + 5000;
20203                    synchronized (conn) {
20204                        long now;
20205                        while (conn.mContainerService == null &&
20206                                (now = SystemClock.uptimeMillis()) < timeout) {
20207                            try {
20208                                conn.wait(timeout - now);
20209                            } catch (InterruptedException e) {
20210                            }
20211                        }
20212                    }
20213                    if (conn.mContainerService == null) {
20214                        return;
20215                    }
20216
20217                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20218                    clearDirectory(conn.mContainerService,
20219                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20220                    if (allData) {
20221                        clearDirectory(conn.mContainerService,
20222                                userEnv.buildExternalStorageAppDataDirs(packageName));
20223                        clearDirectory(conn.mContainerService,
20224                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20225                    }
20226                }
20227            } finally {
20228                mContext.unbindService(conn);
20229            }
20230        }
20231    }
20232
20233    @Override
20234    public void clearApplicationProfileData(String packageName) {
20235        enforceSystemOrRoot("Only the system can clear all profile data");
20236
20237        final PackageParser.Package pkg;
20238        synchronized (mPackages) {
20239            pkg = mPackages.get(packageName);
20240        }
20241
20242        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20243            synchronized (mInstallLock) {
20244                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20245            }
20246        }
20247    }
20248
20249    @Override
20250    public void clearApplicationUserData(final String packageName,
20251            final IPackageDataObserver observer, final int userId) {
20252        mContext.enforceCallingOrSelfPermission(
20253                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20254
20255        final int callingUid = Binder.getCallingUid();
20256        enforceCrossUserPermission(callingUid, userId,
20257                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20258
20259        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20260        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20261        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20262            throw new SecurityException("Cannot clear data for a protected package: "
20263                    + packageName);
20264        }
20265        // Queue up an async operation since the package deletion may take a little while.
20266        mHandler.post(new Runnable() {
20267            public void run() {
20268                mHandler.removeCallbacks(this);
20269                final boolean succeeded;
20270                if (!filterApp) {
20271                    try (PackageFreezer freezer = freezePackage(packageName,
20272                            "clearApplicationUserData")) {
20273                        synchronized (mInstallLock) {
20274                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20275                        }
20276                        clearExternalStorageDataSync(packageName, userId, true);
20277                        synchronized (mPackages) {
20278                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20279                                    packageName, userId);
20280                        }
20281                    }
20282                    if (succeeded) {
20283                        // invoke DeviceStorageMonitor's update method to clear any notifications
20284                        DeviceStorageMonitorInternal dsm = LocalServices
20285                                .getService(DeviceStorageMonitorInternal.class);
20286                        if (dsm != null) {
20287                            dsm.checkMemory();
20288                        }
20289                    }
20290                } else {
20291                    succeeded = false;
20292                }
20293                if (observer != null) {
20294                    try {
20295                        observer.onRemoveCompleted(packageName, succeeded);
20296                    } catch (RemoteException e) {
20297                        Log.i(TAG, "Observer no longer exists.");
20298                    }
20299                } //end if observer
20300            } //end run
20301        });
20302    }
20303
20304    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20305        if (packageName == null) {
20306            Slog.w(TAG, "Attempt to delete null packageName.");
20307            return false;
20308        }
20309
20310        // Try finding details about the requested package
20311        PackageParser.Package pkg;
20312        synchronized (mPackages) {
20313            pkg = mPackages.get(packageName);
20314            if (pkg == null) {
20315                final PackageSetting ps = mSettings.mPackages.get(packageName);
20316                if (ps != null) {
20317                    pkg = ps.pkg;
20318                }
20319            }
20320
20321            if (pkg == null) {
20322                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20323                return false;
20324            }
20325
20326            PackageSetting ps = (PackageSetting) pkg.mExtras;
20327            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20328        }
20329
20330        clearAppDataLIF(pkg, userId,
20331                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20332
20333        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20334        removeKeystoreDataIfNeeded(userId, appId);
20335
20336        UserManagerInternal umInternal = getUserManagerInternal();
20337        final int flags;
20338        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20339            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20340        } else if (umInternal.isUserRunning(userId)) {
20341            flags = StorageManager.FLAG_STORAGE_DE;
20342        } else {
20343            flags = 0;
20344        }
20345        prepareAppDataContentsLIF(pkg, userId, flags);
20346
20347        return true;
20348    }
20349
20350    /**
20351     * Reverts user permission state changes (permissions and flags) in
20352     * all packages for a given user.
20353     *
20354     * @param userId The device user for which to do a reset.
20355     */
20356    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20357        final int packageCount = mPackages.size();
20358        for (int i = 0; i < packageCount; i++) {
20359            PackageParser.Package pkg = mPackages.valueAt(i);
20360            PackageSetting ps = (PackageSetting) pkg.mExtras;
20361            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20362        }
20363    }
20364
20365    private void resetNetworkPolicies(int userId) {
20366        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20367    }
20368
20369    /**
20370     * Reverts user permission state changes (permissions and flags).
20371     *
20372     * @param ps The package for which to reset.
20373     * @param userId The device user for which to do a reset.
20374     */
20375    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20376            final PackageSetting ps, final int userId) {
20377        if (ps.pkg == null) {
20378            return;
20379        }
20380
20381        // These are flags that can change base on user actions.
20382        final int userSettableMask = FLAG_PERMISSION_USER_SET
20383                | FLAG_PERMISSION_USER_FIXED
20384                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20385                | FLAG_PERMISSION_REVIEW_REQUIRED;
20386
20387        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20388                | FLAG_PERMISSION_POLICY_FIXED;
20389
20390        boolean writeInstallPermissions = false;
20391        boolean writeRuntimePermissions = false;
20392
20393        final int permissionCount = ps.pkg.requestedPermissions.size();
20394        for (int i = 0; i < permissionCount; i++) {
20395            final String permissionName = ps.pkg.requestedPermissions.get(i);
20396            final BasePermission bp = mSettings.mPermissions.get(permissionName);
20397            if (bp == null) {
20398                continue;
20399            }
20400
20401            // If shared user we just reset the state to which only this app contributed.
20402            if (ps.sharedUser != null) {
20403                boolean used = false;
20404                final int packageCount = ps.sharedUser.packages.size();
20405                for (int j = 0; j < packageCount; j++) {
20406                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20407                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20408                            && pkg.pkg.requestedPermissions.contains(permissionName)) {
20409                        used = true;
20410                        break;
20411                    }
20412                }
20413                if (used) {
20414                    continue;
20415                }
20416            }
20417
20418            final PermissionsState permissionsState = ps.getPermissionsState();
20419
20420            final int oldFlags = permissionsState.getPermissionFlags(permissionName, userId);
20421
20422            // Always clear the user settable flags.
20423            final boolean hasInstallState =
20424                    permissionsState.getInstallPermissionState(permissionName) != null;
20425            // If permission review is enabled and this is a legacy app, mark the
20426            // permission as requiring a review as this is the initial state.
20427            int flags = 0;
20428            if (mPermissionReviewRequired
20429                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20430                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20431            }
20432            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20433                if (hasInstallState) {
20434                    writeInstallPermissions = true;
20435                } else {
20436                    writeRuntimePermissions = true;
20437                }
20438            }
20439
20440            // Below is only runtime permission handling.
20441            if (!bp.isRuntime()) {
20442                continue;
20443            }
20444
20445            // Never clobber system or policy.
20446            if ((oldFlags & policyOrSystemFlags) != 0) {
20447                continue;
20448            }
20449
20450            // If this permission was granted by default, make sure it is.
20451            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20452                if (permissionsState.grantRuntimePermission(bp, userId)
20453                        != PERMISSION_OPERATION_FAILURE) {
20454                    writeRuntimePermissions = true;
20455                }
20456            // If permission review is enabled the permissions for a legacy apps
20457            // are represented as constantly granted runtime ones, so don't revoke.
20458            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20459                // Otherwise, reset the permission.
20460                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20461                switch (revokeResult) {
20462                    case PERMISSION_OPERATION_SUCCESS:
20463                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20464                        writeRuntimePermissions = true;
20465                        final int appId = ps.appId;
20466                        mHandler.post(new Runnable() {
20467                            @Override
20468                            public void run() {
20469                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20470                            }
20471                        });
20472                    } break;
20473                }
20474            }
20475        }
20476
20477        // Synchronously write as we are taking permissions away.
20478        if (writeRuntimePermissions) {
20479            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20480        }
20481
20482        // Synchronously write as we are taking permissions away.
20483        if (writeInstallPermissions) {
20484            mSettings.writeLPr();
20485        }
20486    }
20487
20488    /**
20489     * Remove entries from the keystore daemon. Will only remove it if the
20490     * {@code appId} is valid.
20491     */
20492    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20493        if (appId < 0) {
20494            return;
20495        }
20496
20497        final KeyStore keyStore = KeyStore.getInstance();
20498        if (keyStore != null) {
20499            if (userId == UserHandle.USER_ALL) {
20500                for (final int individual : sUserManager.getUserIds()) {
20501                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20502                }
20503            } else {
20504                keyStore.clearUid(UserHandle.getUid(userId, appId));
20505            }
20506        } else {
20507            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20508        }
20509    }
20510
20511    @Override
20512    public void deleteApplicationCacheFiles(final String packageName,
20513            final IPackageDataObserver observer) {
20514        final int userId = UserHandle.getCallingUserId();
20515        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20516    }
20517
20518    @Override
20519    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20520            final IPackageDataObserver observer) {
20521        final int callingUid = Binder.getCallingUid();
20522        mContext.enforceCallingOrSelfPermission(
20523                android.Manifest.permission.DELETE_CACHE_FILES, null);
20524        enforceCrossUserPermission(callingUid, userId,
20525                /* requireFullPermission= */ true, /* checkShell= */ false,
20526                "delete application cache files");
20527        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20528                android.Manifest.permission.ACCESS_INSTANT_APPS);
20529
20530        final PackageParser.Package pkg;
20531        synchronized (mPackages) {
20532            pkg = mPackages.get(packageName);
20533        }
20534
20535        // Queue up an async operation since the package deletion may take a little while.
20536        mHandler.post(new Runnable() {
20537            public void run() {
20538                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20539                boolean doClearData = true;
20540                if (ps != null) {
20541                    final boolean targetIsInstantApp =
20542                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20543                    doClearData = !targetIsInstantApp
20544                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20545                }
20546                if (doClearData) {
20547                    synchronized (mInstallLock) {
20548                        final int flags = StorageManager.FLAG_STORAGE_DE
20549                                | StorageManager.FLAG_STORAGE_CE;
20550                        // We're only clearing cache files, so we don't care if the
20551                        // app is unfrozen and still able to run
20552                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20553                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20554                    }
20555                    clearExternalStorageDataSync(packageName, userId, false);
20556                }
20557                if (observer != null) {
20558                    try {
20559                        observer.onRemoveCompleted(packageName, true);
20560                    } catch (RemoteException e) {
20561                        Log.i(TAG, "Observer no longer exists.");
20562                    }
20563                }
20564            }
20565        });
20566    }
20567
20568    @Override
20569    public void getPackageSizeInfo(final String packageName, int userHandle,
20570            final IPackageStatsObserver observer) {
20571        throw new UnsupportedOperationException(
20572                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20573    }
20574
20575    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20576        final PackageSetting ps;
20577        synchronized (mPackages) {
20578            ps = mSettings.mPackages.get(packageName);
20579            if (ps == null) {
20580                Slog.w(TAG, "Failed to find settings for " + packageName);
20581                return false;
20582            }
20583        }
20584
20585        final String[] packageNames = { packageName };
20586        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20587        final String[] codePaths = { ps.codePathString };
20588
20589        try {
20590            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20591                    ps.appId, ceDataInodes, codePaths, stats);
20592
20593            // For now, ignore code size of packages on system partition
20594            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20595                stats.codeSize = 0;
20596            }
20597
20598            // External clients expect these to be tracked separately
20599            stats.dataSize -= stats.cacheSize;
20600
20601        } catch (InstallerException e) {
20602            Slog.w(TAG, String.valueOf(e));
20603            return false;
20604        }
20605
20606        return true;
20607    }
20608
20609    private int getUidTargetSdkVersionLockedLPr(int uid) {
20610        Object obj = mSettings.getUserIdLPr(uid);
20611        if (obj instanceof SharedUserSetting) {
20612            final SharedUserSetting sus = (SharedUserSetting) obj;
20613            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20614            final Iterator<PackageSetting> it = sus.packages.iterator();
20615            while (it.hasNext()) {
20616                final PackageSetting ps = it.next();
20617                if (ps.pkg != null) {
20618                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20619                    if (v < vers) vers = v;
20620                }
20621            }
20622            return vers;
20623        } else if (obj instanceof PackageSetting) {
20624            final PackageSetting ps = (PackageSetting) obj;
20625            if (ps.pkg != null) {
20626                return ps.pkg.applicationInfo.targetSdkVersion;
20627            }
20628        }
20629        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20630    }
20631
20632    @Override
20633    public void addPreferredActivity(IntentFilter filter, int match,
20634            ComponentName[] set, ComponentName activity, int userId) {
20635        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20636                "Adding preferred");
20637    }
20638
20639    private void addPreferredActivityInternal(IntentFilter filter, int match,
20640            ComponentName[] set, ComponentName activity, boolean always, int userId,
20641            String opname) {
20642        // writer
20643        int callingUid = Binder.getCallingUid();
20644        enforceCrossUserPermission(callingUid, userId,
20645                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20646        if (filter.countActions() == 0) {
20647            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20648            return;
20649        }
20650        synchronized (mPackages) {
20651            if (mContext.checkCallingOrSelfPermission(
20652                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20653                    != PackageManager.PERMISSION_GRANTED) {
20654                if (getUidTargetSdkVersionLockedLPr(callingUid)
20655                        < Build.VERSION_CODES.FROYO) {
20656                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20657                            + callingUid);
20658                    return;
20659                }
20660                mContext.enforceCallingOrSelfPermission(
20661                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20662            }
20663
20664            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20665            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20666                    + userId + ":");
20667            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20668            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20669            scheduleWritePackageRestrictionsLocked(userId);
20670            postPreferredActivityChangedBroadcast(userId);
20671        }
20672    }
20673
20674    private void postPreferredActivityChangedBroadcast(int userId) {
20675        mHandler.post(() -> {
20676            final IActivityManager am = ActivityManager.getService();
20677            if (am == null) {
20678                return;
20679            }
20680
20681            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20682            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20683            try {
20684                am.broadcastIntent(null, intent, null, null,
20685                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20686                        null, false, false, userId);
20687            } catch (RemoteException e) {
20688            }
20689        });
20690    }
20691
20692    @Override
20693    public void replacePreferredActivity(IntentFilter filter, int match,
20694            ComponentName[] set, ComponentName activity, int userId) {
20695        if (filter.countActions() != 1) {
20696            throw new IllegalArgumentException(
20697                    "replacePreferredActivity expects filter to have only 1 action.");
20698        }
20699        if (filter.countDataAuthorities() != 0
20700                || filter.countDataPaths() != 0
20701                || filter.countDataSchemes() > 1
20702                || filter.countDataTypes() != 0) {
20703            throw new IllegalArgumentException(
20704                    "replacePreferredActivity expects filter to have no data authorities, " +
20705                    "paths, or types; and at most one scheme.");
20706        }
20707
20708        final int callingUid = Binder.getCallingUid();
20709        enforceCrossUserPermission(callingUid, userId,
20710                true /* requireFullPermission */, false /* checkShell */,
20711                "replace preferred activity");
20712        synchronized (mPackages) {
20713            if (mContext.checkCallingOrSelfPermission(
20714                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20715                    != PackageManager.PERMISSION_GRANTED) {
20716                if (getUidTargetSdkVersionLockedLPr(callingUid)
20717                        < Build.VERSION_CODES.FROYO) {
20718                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20719                            + Binder.getCallingUid());
20720                    return;
20721                }
20722                mContext.enforceCallingOrSelfPermission(
20723                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20724            }
20725
20726            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20727            if (pir != null) {
20728                // Get all of the existing entries that exactly match this filter.
20729                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20730                if (existing != null && existing.size() == 1) {
20731                    PreferredActivity cur = existing.get(0);
20732                    if (DEBUG_PREFERRED) {
20733                        Slog.i(TAG, "Checking replace of preferred:");
20734                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20735                        if (!cur.mPref.mAlways) {
20736                            Slog.i(TAG, "  -- CUR; not mAlways!");
20737                        } else {
20738                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20739                            Slog.i(TAG, "  -- CUR: mSet="
20740                                    + Arrays.toString(cur.mPref.mSetComponents));
20741                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20742                            Slog.i(TAG, "  -- NEW: mMatch="
20743                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20744                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20745                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20746                        }
20747                    }
20748                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20749                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20750                            && cur.mPref.sameSet(set)) {
20751                        // Setting the preferred activity to what it happens to be already
20752                        if (DEBUG_PREFERRED) {
20753                            Slog.i(TAG, "Replacing with same preferred activity "
20754                                    + cur.mPref.mShortComponent + " for user "
20755                                    + userId + ":");
20756                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20757                        }
20758                        return;
20759                    }
20760                }
20761
20762                if (existing != null) {
20763                    if (DEBUG_PREFERRED) {
20764                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20765                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20766                    }
20767                    for (int i = 0; i < existing.size(); i++) {
20768                        PreferredActivity pa = existing.get(i);
20769                        if (DEBUG_PREFERRED) {
20770                            Slog.i(TAG, "Removing existing preferred activity "
20771                                    + pa.mPref.mComponent + ":");
20772                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20773                        }
20774                        pir.removeFilter(pa);
20775                    }
20776                }
20777            }
20778            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20779                    "Replacing preferred");
20780        }
20781    }
20782
20783    @Override
20784    public void clearPackagePreferredActivities(String packageName) {
20785        final int callingUid = Binder.getCallingUid();
20786        if (getInstantAppPackageName(callingUid) != null) {
20787            return;
20788        }
20789        // writer
20790        synchronized (mPackages) {
20791            PackageParser.Package pkg = mPackages.get(packageName);
20792            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20793                if (mContext.checkCallingOrSelfPermission(
20794                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20795                        != PackageManager.PERMISSION_GRANTED) {
20796                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20797                            < Build.VERSION_CODES.FROYO) {
20798                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20799                                + callingUid);
20800                        return;
20801                    }
20802                    mContext.enforceCallingOrSelfPermission(
20803                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20804                }
20805            }
20806            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20807            if (ps != null
20808                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20809                return;
20810            }
20811            int user = UserHandle.getCallingUserId();
20812            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20813                scheduleWritePackageRestrictionsLocked(user);
20814            }
20815        }
20816    }
20817
20818    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20819    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20820        ArrayList<PreferredActivity> removed = null;
20821        boolean changed = false;
20822        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20823            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20824            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20825            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20826                continue;
20827            }
20828            Iterator<PreferredActivity> it = pir.filterIterator();
20829            while (it.hasNext()) {
20830                PreferredActivity pa = it.next();
20831                // Mark entry for removal only if it matches the package name
20832                // and the entry is of type "always".
20833                if (packageName == null ||
20834                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20835                                && pa.mPref.mAlways)) {
20836                    if (removed == null) {
20837                        removed = new ArrayList<PreferredActivity>();
20838                    }
20839                    removed.add(pa);
20840                }
20841            }
20842            if (removed != null) {
20843                for (int j=0; j<removed.size(); j++) {
20844                    PreferredActivity pa = removed.get(j);
20845                    pir.removeFilter(pa);
20846                }
20847                changed = true;
20848            }
20849        }
20850        if (changed) {
20851            postPreferredActivityChangedBroadcast(userId);
20852        }
20853        return changed;
20854    }
20855
20856    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20857    private void clearIntentFilterVerificationsLPw(int userId) {
20858        final int packageCount = mPackages.size();
20859        for (int i = 0; i < packageCount; i++) {
20860            PackageParser.Package pkg = mPackages.valueAt(i);
20861            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20862        }
20863    }
20864
20865    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20866    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20867        if (userId == UserHandle.USER_ALL) {
20868            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20869                    sUserManager.getUserIds())) {
20870                for (int oneUserId : sUserManager.getUserIds()) {
20871                    scheduleWritePackageRestrictionsLocked(oneUserId);
20872                }
20873            }
20874        } else {
20875            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20876                scheduleWritePackageRestrictionsLocked(userId);
20877            }
20878        }
20879    }
20880
20881    /** Clears state for all users, and touches intent filter verification policy */
20882    void clearDefaultBrowserIfNeeded(String packageName) {
20883        for (int oneUserId : sUserManager.getUserIds()) {
20884            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20885        }
20886    }
20887
20888    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20889        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20890        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20891            if (packageName.equals(defaultBrowserPackageName)) {
20892                setDefaultBrowserPackageName(null, userId);
20893            }
20894        }
20895    }
20896
20897    @Override
20898    public void resetApplicationPreferences(int userId) {
20899        mContext.enforceCallingOrSelfPermission(
20900                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20901        final long identity = Binder.clearCallingIdentity();
20902        // writer
20903        try {
20904            synchronized (mPackages) {
20905                clearPackagePreferredActivitiesLPw(null, userId);
20906                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20907                // TODO: We have to reset the default SMS and Phone. This requires
20908                // significant refactoring to keep all default apps in the package
20909                // manager (cleaner but more work) or have the services provide
20910                // callbacks to the package manager to request a default app reset.
20911                applyFactoryDefaultBrowserLPw(userId);
20912                clearIntentFilterVerificationsLPw(userId);
20913                primeDomainVerificationsLPw(userId);
20914                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20915                scheduleWritePackageRestrictionsLocked(userId);
20916            }
20917            resetNetworkPolicies(userId);
20918        } finally {
20919            Binder.restoreCallingIdentity(identity);
20920        }
20921    }
20922
20923    @Override
20924    public int getPreferredActivities(List<IntentFilter> outFilters,
20925            List<ComponentName> outActivities, String packageName) {
20926        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20927            return 0;
20928        }
20929        int num = 0;
20930        final int userId = UserHandle.getCallingUserId();
20931        // reader
20932        synchronized (mPackages) {
20933            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20934            if (pir != null) {
20935                final Iterator<PreferredActivity> it = pir.filterIterator();
20936                while (it.hasNext()) {
20937                    final PreferredActivity pa = it.next();
20938                    if (packageName == null
20939                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20940                                    && pa.mPref.mAlways)) {
20941                        if (outFilters != null) {
20942                            outFilters.add(new IntentFilter(pa));
20943                        }
20944                        if (outActivities != null) {
20945                            outActivities.add(pa.mPref.mComponent);
20946                        }
20947                    }
20948                }
20949            }
20950        }
20951
20952        return num;
20953    }
20954
20955    @Override
20956    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20957            int userId) {
20958        int callingUid = Binder.getCallingUid();
20959        if (callingUid != Process.SYSTEM_UID) {
20960            throw new SecurityException(
20961                    "addPersistentPreferredActivity can only be run by the system");
20962        }
20963        if (filter.countActions() == 0) {
20964            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20965            return;
20966        }
20967        synchronized (mPackages) {
20968            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20969                    ":");
20970            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20971            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20972                    new PersistentPreferredActivity(filter, activity));
20973            scheduleWritePackageRestrictionsLocked(userId);
20974            postPreferredActivityChangedBroadcast(userId);
20975        }
20976    }
20977
20978    @Override
20979    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20980        int callingUid = Binder.getCallingUid();
20981        if (callingUid != Process.SYSTEM_UID) {
20982            throw new SecurityException(
20983                    "clearPackagePersistentPreferredActivities can only be run by the system");
20984        }
20985        ArrayList<PersistentPreferredActivity> removed = null;
20986        boolean changed = false;
20987        synchronized (mPackages) {
20988            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20989                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20990                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20991                        .valueAt(i);
20992                if (userId != thisUserId) {
20993                    continue;
20994                }
20995                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20996                while (it.hasNext()) {
20997                    PersistentPreferredActivity ppa = it.next();
20998                    // Mark entry for removal only if it matches the package name.
20999                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21000                        if (removed == null) {
21001                            removed = new ArrayList<PersistentPreferredActivity>();
21002                        }
21003                        removed.add(ppa);
21004                    }
21005                }
21006                if (removed != null) {
21007                    for (int j=0; j<removed.size(); j++) {
21008                        PersistentPreferredActivity ppa = removed.get(j);
21009                        ppir.removeFilter(ppa);
21010                    }
21011                    changed = true;
21012                }
21013            }
21014
21015            if (changed) {
21016                scheduleWritePackageRestrictionsLocked(userId);
21017                postPreferredActivityChangedBroadcast(userId);
21018            }
21019        }
21020    }
21021
21022    /**
21023     * Common machinery for picking apart a restored XML blob and passing
21024     * it to a caller-supplied functor to be applied to the running system.
21025     */
21026    private void restoreFromXml(XmlPullParser parser, int userId,
21027            String expectedStartTag, BlobXmlRestorer functor)
21028            throws IOException, XmlPullParserException {
21029        int type;
21030        while ((type = parser.next()) != XmlPullParser.START_TAG
21031                && type != XmlPullParser.END_DOCUMENT) {
21032        }
21033        if (type != XmlPullParser.START_TAG) {
21034            // oops didn't find a start tag?!
21035            if (DEBUG_BACKUP) {
21036                Slog.e(TAG, "Didn't find start tag during restore");
21037            }
21038            return;
21039        }
21040Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21041        // this is supposed to be TAG_PREFERRED_BACKUP
21042        if (!expectedStartTag.equals(parser.getName())) {
21043            if (DEBUG_BACKUP) {
21044                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21045            }
21046            return;
21047        }
21048
21049        // skip interfering stuff, then we're aligned with the backing implementation
21050        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21051Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21052        functor.apply(parser, userId);
21053    }
21054
21055    private interface BlobXmlRestorer {
21056        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21057    }
21058
21059    /**
21060     * Non-Binder method, support for the backup/restore mechanism: write the
21061     * full set of preferred activities in its canonical XML format.  Returns the
21062     * XML output as a byte array, or null if there is none.
21063     */
21064    @Override
21065    public byte[] getPreferredActivityBackup(int userId) {
21066        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21067            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21068        }
21069
21070        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21071        try {
21072            final XmlSerializer serializer = new FastXmlSerializer();
21073            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21074            serializer.startDocument(null, true);
21075            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21076
21077            synchronized (mPackages) {
21078                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21079            }
21080
21081            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21082            serializer.endDocument();
21083            serializer.flush();
21084        } catch (Exception e) {
21085            if (DEBUG_BACKUP) {
21086                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21087            }
21088            return null;
21089        }
21090
21091        return dataStream.toByteArray();
21092    }
21093
21094    @Override
21095    public void restorePreferredActivities(byte[] backup, int userId) {
21096        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21097            throw new SecurityException("Only the system may call restorePreferredActivities()");
21098        }
21099
21100        try {
21101            final XmlPullParser parser = Xml.newPullParser();
21102            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21103            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21104                    new BlobXmlRestorer() {
21105                        @Override
21106                        public void apply(XmlPullParser parser, int userId)
21107                                throws XmlPullParserException, IOException {
21108                            synchronized (mPackages) {
21109                                mSettings.readPreferredActivitiesLPw(parser, userId);
21110                            }
21111                        }
21112                    } );
21113        } catch (Exception e) {
21114            if (DEBUG_BACKUP) {
21115                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21116            }
21117        }
21118    }
21119
21120    /**
21121     * Non-Binder method, support for the backup/restore mechanism: write the
21122     * default browser (etc) settings in its canonical XML format.  Returns the default
21123     * browser XML representation as a byte array, or null if there is none.
21124     */
21125    @Override
21126    public byte[] getDefaultAppsBackup(int userId) {
21127        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21128            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21129        }
21130
21131        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21132        try {
21133            final XmlSerializer serializer = new FastXmlSerializer();
21134            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21135            serializer.startDocument(null, true);
21136            serializer.startTag(null, TAG_DEFAULT_APPS);
21137
21138            synchronized (mPackages) {
21139                mSettings.writeDefaultAppsLPr(serializer, userId);
21140            }
21141
21142            serializer.endTag(null, TAG_DEFAULT_APPS);
21143            serializer.endDocument();
21144            serializer.flush();
21145        } catch (Exception e) {
21146            if (DEBUG_BACKUP) {
21147                Slog.e(TAG, "Unable to write default apps for backup", e);
21148            }
21149            return null;
21150        }
21151
21152        return dataStream.toByteArray();
21153    }
21154
21155    @Override
21156    public void restoreDefaultApps(byte[] backup, int userId) {
21157        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21158            throw new SecurityException("Only the system may call restoreDefaultApps()");
21159        }
21160
21161        try {
21162            final XmlPullParser parser = Xml.newPullParser();
21163            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21164            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21165                    new BlobXmlRestorer() {
21166                        @Override
21167                        public void apply(XmlPullParser parser, int userId)
21168                                throws XmlPullParserException, IOException {
21169                            synchronized (mPackages) {
21170                                mSettings.readDefaultAppsLPw(parser, userId);
21171                            }
21172                        }
21173                    } );
21174        } catch (Exception e) {
21175            if (DEBUG_BACKUP) {
21176                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21177            }
21178        }
21179    }
21180
21181    @Override
21182    public byte[] getIntentFilterVerificationBackup(int userId) {
21183        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21184            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21185        }
21186
21187        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21188        try {
21189            final XmlSerializer serializer = new FastXmlSerializer();
21190            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21191            serializer.startDocument(null, true);
21192            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21193
21194            synchronized (mPackages) {
21195                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21196            }
21197
21198            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21199            serializer.endDocument();
21200            serializer.flush();
21201        } catch (Exception e) {
21202            if (DEBUG_BACKUP) {
21203                Slog.e(TAG, "Unable to write default apps for backup", e);
21204            }
21205            return null;
21206        }
21207
21208        return dataStream.toByteArray();
21209    }
21210
21211    @Override
21212    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21213        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21214            throw new SecurityException("Only the system may call restorePreferredActivities()");
21215        }
21216
21217        try {
21218            final XmlPullParser parser = Xml.newPullParser();
21219            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21220            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21221                    new BlobXmlRestorer() {
21222                        @Override
21223                        public void apply(XmlPullParser parser, int userId)
21224                                throws XmlPullParserException, IOException {
21225                            synchronized (mPackages) {
21226                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21227                                mSettings.writeLPr();
21228                            }
21229                        }
21230                    } );
21231        } catch (Exception e) {
21232            if (DEBUG_BACKUP) {
21233                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21234            }
21235        }
21236    }
21237
21238    @Override
21239    public byte[] getPermissionGrantBackup(int userId) {
21240        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21241            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21242        }
21243
21244        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21245        try {
21246            final XmlSerializer serializer = new FastXmlSerializer();
21247            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21248            serializer.startDocument(null, true);
21249            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21250
21251            synchronized (mPackages) {
21252                serializeRuntimePermissionGrantsLPr(serializer, userId);
21253            }
21254
21255            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21256            serializer.endDocument();
21257            serializer.flush();
21258        } catch (Exception e) {
21259            if (DEBUG_BACKUP) {
21260                Slog.e(TAG, "Unable to write default apps for backup", e);
21261            }
21262            return null;
21263        }
21264
21265        return dataStream.toByteArray();
21266    }
21267
21268    @Override
21269    public void restorePermissionGrants(byte[] backup, int userId) {
21270        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21271            throw new SecurityException("Only the system may call restorePermissionGrants()");
21272        }
21273
21274        try {
21275            final XmlPullParser parser = Xml.newPullParser();
21276            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21277            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21278                    new BlobXmlRestorer() {
21279                        @Override
21280                        public void apply(XmlPullParser parser, int userId)
21281                                throws XmlPullParserException, IOException {
21282                            synchronized (mPackages) {
21283                                processRestoredPermissionGrantsLPr(parser, userId);
21284                            }
21285                        }
21286                    } );
21287        } catch (Exception e) {
21288            if (DEBUG_BACKUP) {
21289                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21290            }
21291        }
21292    }
21293
21294    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21295            throws IOException {
21296        serializer.startTag(null, TAG_ALL_GRANTS);
21297
21298        final int N = mSettings.mPackages.size();
21299        for (int i = 0; i < N; i++) {
21300            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21301            boolean pkgGrantsKnown = false;
21302
21303            PermissionsState packagePerms = ps.getPermissionsState();
21304
21305            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21306                final int grantFlags = state.getFlags();
21307                // only look at grants that are not system/policy fixed
21308                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21309                    final boolean isGranted = state.isGranted();
21310                    // And only back up the user-twiddled state bits
21311                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21312                        final String packageName = mSettings.mPackages.keyAt(i);
21313                        if (!pkgGrantsKnown) {
21314                            serializer.startTag(null, TAG_GRANT);
21315                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21316                            pkgGrantsKnown = true;
21317                        }
21318
21319                        final boolean userSet =
21320                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21321                        final boolean userFixed =
21322                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21323                        final boolean revoke =
21324                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21325
21326                        serializer.startTag(null, TAG_PERMISSION);
21327                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21328                        if (isGranted) {
21329                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21330                        }
21331                        if (userSet) {
21332                            serializer.attribute(null, ATTR_USER_SET, "true");
21333                        }
21334                        if (userFixed) {
21335                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21336                        }
21337                        if (revoke) {
21338                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21339                        }
21340                        serializer.endTag(null, TAG_PERMISSION);
21341                    }
21342                }
21343            }
21344
21345            if (pkgGrantsKnown) {
21346                serializer.endTag(null, TAG_GRANT);
21347            }
21348        }
21349
21350        serializer.endTag(null, TAG_ALL_GRANTS);
21351    }
21352
21353    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21354            throws XmlPullParserException, IOException {
21355        String pkgName = null;
21356        int outerDepth = parser.getDepth();
21357        int type;
21358        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21359                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21360            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21361                continue;
21362            }
21363
21364            final String tagName = parser.getName();
21365            if (tagName.equals(TAG_GRANT)) {
21366                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21367                if (DEBUG_BACKUP) {
21368                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21369                }
21370            } else if (tagName.equals(TAG_PERMISSION)) {
21371
21372                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21373                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21374
21375                int newFlagSet = 0;
21376                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21377                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21378                }
21379                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21380                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21381                }
21382                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21383                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21384                }
21385                if (DEBUG_BACKUP) {
21386                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21387                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21388                }
21389                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21390                if (ps != null) {
21391                    // Already installed so we apply the grant immediately
21392                    if (DEBUG_BACKUP) {
21393                        Slog.v(TAG, "        + already installed; applying");
21394                    }
21395                    PermissionsState perms = ps.getPermissionsState();
21396                    BasePermission bp = mSettings.mPermissions.get(permName);
21397                    if (bp != null) {
21398                        if (isGranted) {
21399                            perms.grantRuntimePermission(bp, userId);
21400                        }
21401                        if (newFlagSet != 0) {
21402                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21403                        }
21404                    }
21405                } else {
21406                    // Need to wait for post-restore install to apply the grant
21407                    if (DEBUG_BACKUP) {
21408                        Slog.v(TAG, "        - not yet installed; saving for later");
21409                    }
21410                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21411                            isGranted, newFlagSet, userId);
21412                }
21413            } else {
21414                PackageManagerService.reportSettingsProblem(Log.WARN,
21415                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21416                XmlUtils.skipCurrentTag(parser);
21417            }
21418        }
21419
21420        scheduleWriteSettingsLocked();
21421        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21422    }
21423
21424    @Override
21425    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21426            int sourceUserId, int targetUserId, int flags) {
21427        mContext.enforceCallingOrSelfPermission(
21428                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21429        int callingUid = Binder.getCallingUid();
21430        enforceOwnerRights(ownerPackage, callingUid);
21431        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21432        if (intentFilter.countActions() == 0) {
21433            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21434            return;
21435        }
21436        synchronized (mPackages) {
21437            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21438                    ownerPackage, targetUserId, flags);
21439            CrossProfileIntentResolver resolver =
21440                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21441            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21442            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21443            if (existing != null) {
21444                int size = existing.size();
21445                for (int i = 0; i < size; i++) {
21446                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21447                        return;
21448                    }
21449                }
21450            }
21451            resolver.addFilter(newFilter);
21452            scheduleWritePackageRestrictionsLocked(sourceUserId);
21453        }
21454    }
21455
21456    @Override
21457    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21458        mContext.enforceCallingOrSelfPermission(
21459                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21460        final int callingUid = Binder.getCallingUid();
21461        enforceOwnerRights(ownerPackage, callingUid);
21462        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21463        synchronized (mPackages) {
21464            CrossProfileIntentResolver resolver =
21465                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21466            ArraySet<CrossProfileIntentFilter> set =
21467                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21468            for (CrossProfileIntentFilter filter : set) {
21469                if (filter.getOwnerPackage().equals(ownerPackage)) {
21470                    resolver.removeFilter(filter);
21471                }
21472            }
21473            scheduleWritePackageRestrictionsLocked(sourceUserId);
21474        }
21475    }
21476
21477    // Enforcing that callingUid is owning pkg on userId
21478    private void enforceOwnerRights(String pkg, int callingUid) {
21479        // The system owns everything.
21480        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21481            return;
21482        }
21483        final int callingUserId = UserHandle.getUserId(callingUid);
21484        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21485        if (pi == null) {
21486            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21487                    + callingUserId);
21488        }
21489        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21490            throw new SecurityException("Calling uid " + callingUid
21491                    + " does not own package " + pkg);
21492        }
21493    }
21494
21495    @Override
21496    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21497        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21498            return null;
21499        }
21500        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21501    }
21502
21503    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21504        UserManagerService ums = UserManagerService.getInstance();
21505        if (ums != null) {
21506            final UserInfo parent = ums.getProfileParent(userId);
21507            final int launcherUid = (parent != null) ? parent.id : userId;
21508            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21509            if (launcherComponent != null) {
21510                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21511                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21512                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21513                        .setPackage(launcherComponent.getPackageName());
21514                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21515            }
21516        }
21517    }
21518
21519    /**
21520     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21521     * then reports the most likely home activity or null if there are more than one.
21522     */
21523    private ComponentName getDefaultHomeActivity(int userId) {
21524        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21525        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21526        if (cn != null) {
21527            return cn;
21528        }
21529
21530        // Find the launcher with the highest priority and return that component if there are no
21531        // other home activity with the same priority.
21532        int lastPriority = Integer.MIN_VALUE;
21533        ComponentName lastComponent = null;
21534        final int size = allHomeCandidates.size();
21535        for (int i = 0; i < size; i++) {
21536            final ResolveInfo ri = allHomeCandidates.get(i);
21537            if (ri.priority > lastPriority) {
21538                lastComponent = ri.activityInfo.getComponentName();
21539                lastPriority = ri.priority;
21540            } else if (ri.priority == lastPriority) {
21541                // Two components found with same priority.
21542                lastComponent = null;
21543            }
21544        }
21545        return lastComponent;
21546    }
21547
21548    private Intent getHomeIntent() {
21549        Intent intent = new Intent(Intent.ACTION_MAIN);
21550        intent.addCategory(Intent.CATEGORY_HOME);
21551        intent.addCategory(Intent.CATEGORY_DEFAULT);
21552        return intent;
21553    }
21554
21555    private IntentFilter getHomeFilter() {
21556        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21557        filter.addCategory(Intent.CATEGORY_HOME);
21558        filter.addCategory(Intent.CATEGORY_DEFAULT);
21559        return filter;
21560    }
21561
21562    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21563            int userId) {
21564        Intent intent  = getHomeIntent();
21565        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21566                PackageManager.GET_META_DATA, userId);
21567        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21568                true, false, false, userId);
21569
21570        allHomeCandidates.clear();
21571        if (list != null) {
21572            for (ResolveInfo ri : list) {
21573                allHomeCandidates.add(ri);
21574            }
21575        }
21576        return (preferred == null || preferred.activityInfo == null)
21577                ? null
21578                : new ComponentName(preferred.activityInfo.packageName,
21579                        preferred.activityInfo.name);
21580    }
21581
21582    @Override
21583    public void setHomeActivity(ComponentName comp, int userId) {
21584        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21585            return;
21586        }
21587        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21588        getHomeActivitiesAsUser(homeActivities, userId);
21589
21590        boolean found = false;
21591
21592        final int size = homeActivities.size();
21593        final ComponentName[] set = new ComponentName[size];
21594        for (int i = 0; i < size; i++) {
21595            final ResolveInfo candidate = homeActivities.get(i);
21596            final ActivityInfo info = candidate.activityInfo;
21597            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21598            set[i] = activityName;
21599            if (!found && activityName.equals(comp)) {
21600                found = true;
21601            }
21602        }
21603        if (!found) {
21604            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21605                    + userId);
21606        }
21607        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21608                set, comp, userId);
21609    }
21610
21611    private @Nullable String getSetupWizardPackageName() {
21612        final Intent intent = new Intent(Intent.ACTION_MAIN);
21613        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21614
21615        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21616                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21617                        | MATCH_DISABLED_COMPONENTS,
21618                UserHandle.myUserId());
21619        if (matches.size() == 1) {
21620            return matches.get(0).getComponentInfo().packageName;
21621        } else {
21622            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21623                    + ": matches=" + matches);
21624            return null;
21625        }
21626    }
21627
21628    private @Nullable String getStorageManagerPackageName() {
21629        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21630
21631        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21632                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21633                        | MATCH_DISABLED_COMPONENTS,
21634                UserHandle.myUserId());
21635        if (matches.size() == 1) {
21636            return matches.get(0).getComponentInfo().packageName;
21637        } else {
21638            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21639                    + matches.size() + ": matches=" + matches);
21640            return null;
21641        }
21642    }
21643
21644    @Override
21645    public void setApplicationEnabledSetting(String appPackageName,
21646            int newState, int flags, int userId, String callingPackage) {
21647        if (!sUserManager.exists(userId)) return;
21648        if (callingPackage == null) {
21649            callingPackage = Integer.toString(Binder.getCallingUid());
21650        }
21651        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21652    }
21653
21654    @Override
21655    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21656        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21657        synchronized (mPackages) {
21658            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21659            if (pkgSetting != null) {
21660                pkgSetting.setUpdateAvailable(updateAvailable);
21661            }
21662        }
21663    }
21664
21665    @Override
21666    public void setComponentEnabledSetting(ComponentName componentName,
21667            int newState, int flags, int userId) {
21668        if (!sUserManager.exists(userId)) return;
21669        setEnabledSetting(componentName.getPackageName(),
21670                componentName.getClassName(), newState, flags, userId, null);
21671    }
21672
21673    private void setEnabledSetting(final String packageName, String className, int newState,
21674            final int flags, int userId, String callingPackage) {
21675        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21676              || newState == COMPONENT_ENABLED_STATE_ENABLED
21677              || newState == COMPONENT_ENABLED_STATE_DISABLED
21678              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21679              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21680            throw new IllegalArgumentException("Invalid new component state: "
21681                    + newState);
21682        }
21683        PackageSetting pkgSetting;
21684        final int callingUid = Binder.getCallingUid();
21685        final int permission;
21686        if (callingUid == Process.SYSTEM_UID) {
21687            permission = PackageManager.PERMISSION_GRANTED;
21688        } else {
21689            permission = mContext.checkCallingOrSelfPermission(
21690                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21691        }
21692        enforceCrossUserPermission(callingUid, userId,
21693                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21694        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21695        boolean sendNow = false;
21696        boolean isApp = (className == null);
21697        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21698        String componentName = isApp ? packageName : className;
21699        int packageUid = -1;
21700        ArrayList<String> components;
21701
21702        // reader
21703        synchronized (mPackages) {
21704            pkgSetting = mSettings.mPackages.get(packageName);
21705            if (pkgSetting == null) {
21706                if (!isCallerInstantApp) {
21707                    if (className == null) {
21708                        throw new IllegalArgumentException("Unknown package: " + packageName);
21709                    }
21710                    throw new IllegalArgumentException(
21711                            "Unknown component: " + packageName + "/" + className);
21712                } else {
21713                    // throw SecurityException to prevent leaking package information
21714                    throw new SecurityException(
21715                            "Attempt to change component state; "
21716                            + "pid=" + Binder.getCallingPid()
21717                            + ", uid=" + callingUid
21718                            + (className == null
21719                                    ? ", package=" + packageName
21720                                    : ", component=" + packageName + "/" + className));
21721                }
21722            }
21723        }
21724
21725        // Limit who can change which apps
21726        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21727            // Don't allow apps that don't have permission to modify other apps
21728            if (!allowedByPermission
21729                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21730                throw new SecurityException(
21731                        "Attempt to change component state; "
21732                        + "pid=" + Binder.getCallingPid()
21733                        + ", uid=" + callingUid
21734                        + (className == null
21735                                ? ", package=" + packageName
21736                                : ", component=" + packageName + "/" + className));
21737            }
21738            // Don't allow changing protected packages.
21739            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21740                throw new SecurityException("Cannot disable a protected package: " + packageName);
21741            }
21742        }
21743
21744        synchronized (mPackages) {
21745            if (callingUid == Process.SHELL_UID
21746                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21747                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21748                // unless it is a test package.
21749                int oldState = pkgSetting.getEnabled(userId);
21750                if (className == null
21751                        &&
21752                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21753                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21754                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21755                        &&
21756                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21757                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21758                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21759                    // ok
21760                } else {
21761                    throw new SecurityException(
21762                            "Shell cannot change component state for " + packageName + "/"
21763                                    + className + " to " + newState);
21764                }
21765            }
21766        }
21767        if (className == null) {
21768            // We're dealing with an application/package level state change
21769            synchronized (mPackages) {
21770                if (pkgSetting.getEnabled(userId) == newState) {
21771                    // Nothing to do
21772                    return;
21773                }
21774            }
21775            // If we're enabling a system stub, there's a little more work to do.
21776            // Prior to enabling the package, we need to decompress the APK(s) to the
21777            // data partition and then replace the version on the system partition.
21778            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21779            final boolean isSystemStub = deletedPkg.isStub
21780                    && deletedPkg.isSystemApp();
21781            if (isSystemStub
21782                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21783                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21784                final File codePath = decompressPackage(deletedPkg);
21785                if (codePath == null) {
21786                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21787                    return;
21788                }
21789                // TODO remove direct parsing of the package object during internal cleanup
21790                // of scan package
21791                // We need to call parse directly here for no other reason than we need
21792                // the new package in order to disable the old one [we use the information
21793                // for some internal optimization to optionally create a new package setting
21794                // object on replace]. However, we can't get the package from the scan
21795                // because the scan modifies live structures and we need to remove the
21796                // old [system] package from the system before a scan can be attempted.
21797                // Once scan is indempotent we can remove this parse and use the package
21798                // object we scanned, prior to adding it to package settings.
21799                final PackageParser pp = new PackageParser();
21800                pp.setSeparateProcesses(mSeparateProcesses);
21801                pp.setDisplayMetrics(mMetrics);
21802                pp.setCallback(mPackageParserCallback);
21803                final PackageParser.Package tmpPkg;
21804                try {
21805                    final int parseFlags = mDefParseFlags
21806                            | PackageParser.PARSE_MUST_BE_APK
21807                            | PackageParser.PARSE_IS_SYSTEM
21808                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21809                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21810                } catch (PackageParserException e) {
21811                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21812                    return;
21813                }
21814                synchronized (mInstallLock) {
21815                    // Disable the stub and remove any package entries
21816                    removePackageLI(deletedPkg, true);
21817                    synchronized (mPackages) {
21818                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21819                    }
21820                    final PackageParser.Package newPkg;
21821                    try (PackageFreezer freezer =
21822                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21823                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21824                                | PackageParser.PARSE_ENFORCE_CODE;
21825                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21826                                0 /*currentTime*/, null /*user*/);
21827                        prepareAppDataAfterInstallLIF(newPkg);
21828                        synchronized (mPackages) {
21829                            try {
21830                                updateSharedLibrariesLPr(newPkg, null);
21831                            } catch (PackageManagerException e) {
21832                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21833                            }
21834                            updatePermissionsLPw(newPkg.packageName, newPkg,
21835                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21836                            mSettings.writeLPr();
21837                        }
21838                    } catch (PackageManagerException e) {
21839                        // Whoops! Something went wrong; try to roll back to the stub
21840                        Slog.w(TAG, "Failed to install compressed system package:"
21841                                + pkgSetting.name, e);
21842                        // Remove the failed install
21843                        removeCodePathLI(codePath);
21844
21845                        // Install the system package
21846                        try (PackageFreezer freezer =
21847                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21848                            synchronized (mPackages) {
21849                                // NOTE: The system package always needs to be enabled; even
21850                                // if it's for a compressed stub. If we don't, installing the
21851                                // system package fails during scan [scanning checks the disabled
21852                                // packages]. We will reverse this later, after we've "installed"
21853                                // the stub.
21854                                // This leaves us in a fragile state; the stub should never be
21855                                // enabled, so, cross your fingers and hope nothing goes wrong
21856                                // until we can disable the package later.
21857                                enableSystemPackageLPw(deletedPkg);
21858                            }
21859                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21860                                    false /*isPrivileged*/, null /*allUserHandles*/,
21861                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21862                                    true /*writeSettings*/);
21863                        } catch (PackageManagerException pme) {
21864                            Slog.w(TAG, "Failed to restore system package:"
21865                                    + deletedPkg.packageName, pme);
21866                        } finally {
21867                            synchronized (mPackages) {
21868                                mSettings.disableSystemPackageLPw(
21869                                        deletedPkg.packageName, true /*replaced*/);
21870                                mSettings.writeLPr();
21871                            }
21872                        }
21873                        return;
21874                    }
21875                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21876                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21877                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21878                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21879                            newPkg.baseCodePath, newPkg.splitCodePaths);
21880                }
21881            }
21882            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21883                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21884                // Don't care about who enables an app.
21885                callingPackage = null;
21886            }
21887            synchronized (mPackages) {
21888                pkgSetting.setEnabled(newState, userId, callingPackage);
21889            }
21890        } else {
21891            synchronized (mPackages) {
21892                // We're dealing with a component level state change
21893                // First, verify that this is a valid class name.
21894                PackageParser.Package pkg = pkgSetting.pkg;
21895                if (pkg == null || !pkg.hasComponentClassName(className)) {
21896                    if (pkg != null &&
21897                            pkg.applicationInfo.targetSdkVersion >=
21898                                    Build.VERSION_CODES.JELLY_BEAN) {
21899                        throw new IllegalArgumentException("Component class " + className
21900                                + " does not exist in " + packageName);
21901                    } else {
21902                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21903                                + className + " does not exist in " + packageName);
21904                    }
21905                }
21906                switch (newState) {
21907                    case COMPONENT_ENABLED_STATE_ENABLED:
21908                        if (!pkgSetting.enableComponentLPw(className, userId)) {
21909                            return;
21910                        }
21911                        break;
21912                    case COMPONENT_ENABLED_STATE_DISABLED:
21913                        if (!pkgSetting.disableComponentLPw(className, userId)) {
21914                            return;
21915                        }
21916                        break;
21917                    case COMPONENT_ENABLED_STATE_DEFAULT:
21918                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
21919                            return;
21920                        }
21921                        break;
21922                    default:
21923                        Slog.e(TAG, "Invalid new component state: " + newState);
21924                        return;
21925                }
21926            }
21927        }
21928        synchronized (mPackages) {
21929            scheduleWritePackageRestrictionsLocked(userId);
21930            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21931            final long callingId = Binder.clearCallingIdentity();
21932            try {
21933                updateInstantAppInstallerLocked(packageName);
21934            } finally {
21935                Binder.restoreCallingIdentity(callingId);
21936            }
21937            components = mPendingBroadcasts.get(userId, packageName);
21938            final boolean newPackage = components == null;
21939            if (newPackage) {
21940                components = new ArrayList<String>();
21941            }
21942            if (!components.contains(componentName)) {
21943                components.add(componentName);
21944            }
21945            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21946                sendNow = true;
21947                // Purge entry from pending broadcast list if another one exists already
21948                // since we are sending one right away.
21949                mPendingBroadcasts.remove(userId, packageName);
21950            } else {
21951                if (newPackage) {
21952                    mPendingBroadcasts.put(userId, packageName, components);
21953                }
21954                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21955                    // Schedule a message
21956                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21957                }
21958            }
21959        }
21960
21961        long callingId = Binder.clearCallingIdentity();
21962        try {
21963            if (sendNow) {
21964                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21965                sendPackageChangedBroadcast(packageName,
21966                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21967            }
21968        } finally {
21969            Binder.restoreCallingIdentity(callingId);
21970        }
21971    }
21972
21973    @Override
21974    public void flushPackageRestrictionsAsUser(int userId) {
21975        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21976            return;
21977        }
21978        if (!sUserManager.exists(userId)) {
21979            return;
21980        }
21981        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21982                false /* checkShell */, "flushPackageRestrictions");
21983        synchronized (mPackages) {
21984            mSettings.writePackageRestrictionsLPr(userId);
21985            mDirtyUsers.remove(userId);
21986            if (mDirtyUsers.isEmpty()) {
21987                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21988            }
21989        }
21990    }
21991
21992    private void sendPackageChangedBroadcast(String packageName,
21993            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21994        if (DEBUG_INSTALL)
21995            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21996                    + componentNames);
21997        Bundle extras = new Bundle(4);
21998        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21999        String nameList[] = new String[componentNames.size()];
22000        componentNames.toArray(nameList);
22001        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22002        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22003        extras.putInt(Intent.EXTRA_UID, packageUid);
22004        // If this is not reporting a change of the overall package, then only send it
22005        // to registered receivers.  We don't want to launch a swath of apps for every
22006        // little component state change.
22007        final int flags = !componentNames.contains(packageName)
22008                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22009        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22010                new int[] {UserHandle.getUserId(packageUid)});
22011    }
22012
22013    @Override
22014    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22015        if (!sUserManager.exists(userId)) return;
22016        final int callingUid = Binder.getCallingUid();
22017        if (getInstantAppPackageName(callingUid) != null) {
22018            return;
22019        }
22020        final int permission = mContext.checkCallingOrSelfPermission(
22021                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22022        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22023        enforceCrossUserPermission(callingUid, userId,
22024                true /* requireFullPermission */, true /* checkShell */, "stop package");
22025        // writer
22026        synchronized (mPackages) {
22027            final PackageSetting ps = mSettings.mPackages.get(packageName);
22028            if (!filterAppAccessLPr(ps, callingUid, userId)
22029                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22030                            allowedByPermission, callingUid, userId)) {
22031                scheduleWritePackageRestrictionsLocked(userId);
22032            }
22033        }
22034    }
22035
22036    @Override
22037    public String getInstallerPackageName(String packageName) {
22038        final int callingUid = Binder.getCallingUid();
22039        if (getInstantAppPackageName(callingUid) != null) {
22040            return null;
22041        }
22042        // reader
22043        synchronized (mPackages) {
22044            final PackageSetting ps = mSettings.mPackages.get(packageName);
22045            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22046                return null;
22047            }
22048            return mSettings.getInstallerPackageNameLPr(packageName);
22049        }
22050    }
22051
22052    public boolean isOrphaned(String packageName) {
22053        // reader
22054        synchronized (mPackages) {
22055            return mSettings.isOrphaned(packageName);
22056        }
22057    }
22058
22059    @Override
22060    public int getApplicationEnabledSetting(String packageName, int userId) {
22061        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22062        int callingUid = Binder.getCallingUid();
22063        enforceCrossUserPermission(callingUid, userId,
22064                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22065        // reader
22066        synchronized (mPackages) {
22067            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22068                return COMPONENT_ENABLED_STATE_DISABLED;
22069            }
22070            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22071        }
22072    }
22073
22074    @Override
22075    public int getComponentEnabledSetting(ComponentName component, int userId) {
22076        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22077        int callingUid = Binder.getCallingUid();
22078        enforceCrossUserPermission(callingUid, userId,
22079                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22080        synchronized (mPackages) {
22081            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22082                    component, TYPE_UNKNOWN, userId)) {
22083                return COMPONENT_ENABLED_STATE_DISABLED;
22084            }
22085            return mSettings.getComponentEnabledSettingLPr(component, userId);
22086        }
22087    }
22088
22089    @Override
22090    public void enterSafeMode() {
22091        enforceSystemOrRoot("Only the system can request entering safe mode");
22092
22093        if (!mSystemReady) {
22094            mSafeMode = true;
22095        }
22096    }
22097
22098    @Override
22099    public void systemReady() {
22100        enforceSystemOrRoot("Only the system can claim the system is ready");
22101
22102        mSystemReady = true;
22103        final ContentResolver resolver = mContext.getContentResolver();
22104        ContentObserver co = new ContentObserver(mHandler) {
22105            @Override
22106            public void onChange(boolean selfChange) {
22107                mEphemeralAppsDisabled =
22108                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22109                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22110            }
22111        };
22112        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22113                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22114                false, co, UserHandle.USER_SYSTEM);
22115        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22116                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22117        co.onChange(true);
22118
22119        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22120        // disabled after already being started.
22121        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22122                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22123
22124        // Read the compatibilty setting when the system is ready.
22125        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22126                mContext.getContentResolver(),
22127                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22128        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22129        if (DEBUG_SETTINGS) {
22130            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22131        }
22132
22133        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22134
22135        synchronized (mPackages) {
22136            // Verify that all of the preferred activity components actually
22137            // exist.  It is possible for applications to be updated and at
22138            // that point remove a previously declared activity component that
22139            // had been set as a preferred activity.  We try to clean this up
22140            // the next time we encounter that preferred activity, but it is
22141            // possible for the user flow to never be able to return to that
22142            // situation so here we do a sanity check to make sure we haven't
22143            // left any junk around.
22144            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22145            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22146                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22147                removed.clear();
22148                for (PreferredActivity pa : pir.filterSet()) {
22149                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22150                        removed.add(pa);
22151                    }
22152                }
22153                if (removed.size() > 0) {
22154                    for (int r=0; r<removed.size(); r++) {
22155                        PreferredActivity pa = removed.get(r);
22156                        Slog.w(TAG, "Removing dangling preferred activity: "
22157                                + pa.mPref.mComponent);
22158                        pir.removeFilter(pa);
22159                    }
22160                    mSettings.writePackageRestrictionsLPr(
22161                            mSettings.mPreferredActivities.keyAt(i));
22162                }
22163            }
22164
22165            for (int userId : UserManagerService.getInstance().getUserIds()) {
22166                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22167                    grantPermissionsUserIds = ArrayUtils.appendInt(
22168                            grantPermissionsUserIds, userId);
22169                }
22170            }
22171        }
22172        sUserManager.systemReady();
22173
22174        synchronized(mPackages) {
22175            // If we upgraded grant all default permissions before kicking off.
22176            for (int userId : grantPermissionsUserIds) {
22177                mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
22178            }
22179        }
22180
22181        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22182            // If we did not grant default permissions, we preload from this the
22183            // default permission exceptions lazily to ensure we don't hit the
22184            // disk on a new user creation.
22185            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22186        }
22187
22188        // Now that we've scanned all packages, and granted any default
22189        // permissions, ensure permissions are updated. Beware of dragons if you
22190        // try optimizing this.
22191        synchronized (mPackages) {
22192            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
22193                    UPDATE_PERMISSIONS_ALL);
22194        }
22195
22196        // Kick off any messages waiting for system ready
22197        if (mPostSystemReadyMessages != null) {
22198            for (Message msg : mPostSystemReadyMessages) {
22199                msg.sendToTarget();
22200            }
22201            mPostSystemReadyMessages = null;
22202        }
22203
22204        // Watch for external volumes that come and go over time
22205        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22206        storage.registerListener(mStorageListener);
22207
22208        mInstallerService.systemReady();
22209        mPackageDexOptimizer.systemReady();
22210
22211        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22212                StorageManagerInternal.class);
22213        StorageManagerInternal.addExternalStoragePolicy(
22214                new StorageManagerInternal.ExternalStorageMountPolicy() {
22215            @Override
22216            public int getMountMode(int uid, String packageName) {
22217                if (Process.isIsolated(uid)) {
22218                    return Zygote.MOUNT_EXTERNAL_NONE;
22219                }
22220                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22221                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22222                }
22223                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22224                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22225                }
22226                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22227                    return Zygote.MOUNT_EXTERNAL_READ;
22228                }
22229                return Zygote.MOUNT_EXTERNAL_WRITE;
22230            }
22231
22232            @Override
22233            public boolean hasExternalStorage(int uid, String packageName) {
22234                return true;
22235            }
22236        });
22237
22238        // Now that we're mostly running, clean up stale users and apps
22239        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22240        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22241
22242        if (mPrivappPermissionsViolations != null) {
22243            Slog.wtf(TAG,"Signature|privileged permissions not in "
22244                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22245            mPrivappPermissionsViolations = null;
22246        }
22247    }
22248
22249    public void waitForAppDataPrepared() {
22250        if (mPrepareAppDataFuture == null) {
22251            return;
22252        }
22253        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22254        mPrepareAppDataFuture = null;
22255    }
22256
22257    @Override
22258    public boolean isSafeMode() {
22259        // allow instant applications
22260        return mSafeMode;
22261    }
22262
22263    @Override
22264    public boolean hasSystemUidErrors() {
22265        // allow instant applications
22266        return mHasSystemUidErrors;
22267    }
22268
22269    static String arrayToString(int[] array) {
22270        StringBuffer buf = new StringBuffer(128);
22271        buf.append('[');
22272        if (array != null) {
22273            for (int i=0; i<array.length; i++) {
22274                if (i > 0) buf.append(", ");
22275                buf.append(array[i]);
22276            }
22277        }
22278        buf.append(']');
22279        return buf.toString();
22280    }
22281
22282    @Override
22283    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22284            FileDescriptor err, String[] args, ShellCallback callback,
22285            ResultReceiver resultReceiver) {
22286        (new PackageManagerShellCommand(this)).exec(
22287                this, in, out, err, args, callback, resultReceiver);
22288    }
22289
22290    @Override
22291    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22292        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22293
22294        DumpState dumpState = new DumpState();
22295        boolean fullPreferred = false;
22296        boolean checkin = false;
22297
22298        String packageName = null;
22299        ArraySet<String> permissionNames = null;
22300
22301        int opti = 0;
22302        while (opti < args.length) {
22303            String opt = args[opti];
22304            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22305                break;
22306            }
22307            opti++;
22308
22309            if ("-a".equals(opt)) {
22310                // Right now we only know how to print all.
22311            } else if ("-h".equals(opt)) {
22312                pw.println("Package manager dump options:");
22313                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22314                pw.println("    --checkin: dump for a checkin");
22315                pw.println("    -f: print details of intent filters");
22316                pw.println("    -h: print this help");
22317                pw.println("  cmd may be one of:");
22318                pw.println("    l[ibraries]: list known shared libraries");
22319                pw.println("    f[eatures]: list device features");
22320                pw.println("    k[eysets]: print known keysets");
22321                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22322                pw.println("    perm[issions]: dump permissions");
22323                pw.println("    permission [name ...]: dump declaration and use of given permission");
22324                pw.println("    pref[erred]: print preferred package settings");
22325                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22326                pw.println("    prov[iders]: dump content providers");
22327                pw.println("    p[ackages]: dump installed packages");
22328                pw.println("    s[hared-users]: dump shared user IDs");
22329                pw.println("    m[essages]: print collected runtime messages");
22330                pw.println("    v[erifiers]: print package verifier info");
22331                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22332                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22333                pw.println("    version: print database version info");
22334                pw.println("    write: write current settings now");
22335                pw.println("    installs: details about install sessions");
22336                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22337                pw.println("    dexopt: dump dexopt state");
22338                pw.println("    compiler-stats: dump compiler statistics");
22339                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22340                pw.println("    <package.name>: info about given package");
22341                return;
22342            } else if ("--checkin".equals(opt)) {
22343                checkin = true;
22344            } else if ("-f".equals(opt)) {
22345                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22346            } else if ("--proto".equals(opt)) {
22347                dumpProto(fd);
22348                return;
22349            } else {
22350                pw.println("Unknown argument: " + opt + "; use -h for help");
22351            }
22352        }
22353
22354        // Is the caller requesting to dump a particular piece of data?
22355        if (opti < args.length) {
22356            String cmd = args[opti];
22357            opti++;
22358            // Is this a package name?
22359            if ("android".equals(cmd) || cmd.contains(".")) {
22360                packageName = cmd;
22361                // When dumping a single package, we always dump all of its
22362                // filter information since the amount of data will be reasonable.
22363                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22364            } else if ("check-permission".equals(cmd)) {
22365                if (opti >= args.length) {
22366                    pw.println("Error: check-permission missing permission argument");
22367                    return;
22368                }
22369                String perm = args[opti];
22370                opti++;
22371                if (opti >= args.length) {
22372                    pw.println("Error: check-permission missing package argument");
22373                    return;
22374                }
22375
22376                String pkg = args[opti];
22377                opti++;
22378                int user = UserHandle.getUserId(Binder.getCallingUid());
22379                if (opti < args.length) {
22380                    try {
22381                        user = Integer.parseInt(args[opti]);
22382                    } catch (NumberFormatException e) {
22383                        pw.println("Error: check-permission user argument is not a number: "
22384                                + args[opti]);
22385                        return;
22386                    }
22387                }
22388
22389                // Normalize package name to handle renamed packages and static libs
22390                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22391
22392                pw.println(checkPermission(perm, pkg, user));
22393                return;
22394            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22395                dumpState.setDump(DumpState.DUMP_LIBS);
22396            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22397                dumpState.setDump(DumpState.DUMP_FEATURES);
22398            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22399                if (opti >= args.length) {
22400                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22401                            | DumpState.DUMP_SERVICE_RESOLVERS
22402                            | DumpState.DUMP_RECEIVER_RESOLVERS
22403                            | DumpState.DUMP_CONTENT_RESOLVERS);
22404                } else {
22405                    while (opti < args.length) {
22406                        String name = args[opti];
22407                        if ("a".equals(name) || "activity".equals(name)) {
22408                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22409                        } else if ("s".equals(name) || "service".equals(name)) {
22410                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22411                        } else if ("r".equals(name) || "receiver".equals(name)) {
22412                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22413                        } else if ("c".equals(name) || "content".equals(name)) {
22414                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22415                        } else {
22416                            pw.println("Error: unknown resolver table type: " + name);
22417                            return;
22418                        }
22419                        opti++;
22420                    }
22421                }
22422            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22423                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22424            } else if ("permission".equals(cmd)) {
22425                if (opti >= args.length) {
22426                    pw.println("Error: permission requires permission name");
22427                    return;
22428                }
22429                permissionNames = new ArraySet<>();
22430                while (opti < args.length) {
22431                    permissionNames.add(args[opti]);
22432                    opti++;
22433                }
22434                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22435                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22436            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22437                dumpState.setDump(DumpState.DUMP_PREFERRED);
22438            } else if ("preferred-xml".equals(cmd)) {
22439                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22440                if (opti < args.length && "--full".equals(args[opti])) {
22441                    fullPreferred = true;
22442                    opti++;
22443                }
22444            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22445                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22446            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22447                dumpState.setDump(DumpState.DUMP_PACKAGES);
22448            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22449                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22450            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22451                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22452            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22453                dumpState.setDump(DumpState.DUMP_MESSAGES);
22454            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22455                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22456            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22457                    || "intent-filter-verifiers".equals(cmd)) {
22458                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22459            } else if ("version".equals(cmd)) {
22460                dumpState.setDump(DumpState.DUMP_VERSION);
22461            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22462                dumpState.setDump(DumpState.DUMP_KEYSETS);
22463            } else if ("installs".equals(cmd)) {
22464                dumpState.setDump(DumpState.DUMP_INSTALLS);
22465            } else if ("frozen".equals(cmd)) {
22466                dumpState.setDump(DumpState.DUMP_FROZEN);
22467            } else if ("volumes".equals(cmd)) {
22468                dumpState.setDump(DumpState.DUMP_VOLUMES);
22469            } else if ("dexopt".equals(cmd)) {
22470                dumpState.setDump(DumpState.DUMP_DEXOPT);
22471            } else if ("compiler-stats".equals(cmd)) {
22472                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22473            } else if ("changes".equals(cmd)) {
22474                dumpState.setDump(DumpState.DUMP_CHANGES);
22475            } else if ("write".equals(cmd)) {
22476                synchronized (mPackages) {
22477                    mSettings.writeLPr();
22478                    pw.println("Settings written.");
22479                    return;
22480                }
22481            }
22482        }
22483
22484        if (checkin) {
22485            pw.println("vers,1");
22486        }
22487
22488        // reader
22489        synchronized (mPackages) {
22490            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22491                if (!checkin) {
22492                    if (dumpState.onTitlePrinted())
22493                        pw.println();
22494                    pw.println("Database versions:");
22495                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22496                }
22497            }
22498
22499            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22500                if (!checkin) {
22501                    if (dumpState.onTitlePrinted())
22502                        pw.println();
22503                    pw.println("Verifiers:");
22504                    pw.print("  Required: ");
22505                    pw.print(mRequiredVerifierPackage);
22506                    pw.print(" (uid=");
22507                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22508                            UserHandle.USER_SYSTEM));
22509                    pw.println(")");
22510                } else if (mRequiredVerifierPackage != null) {
22511                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22512                    pw.print(",");
22513                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22514                            UserHandle.USER_SYSTEM));
22515                }
22516            }
22517
22518            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22519                    packageName == null) {
22520                if (mIntentFilterVerifierComponent != null) {
22521                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22522                    if (!checkin) {
22523                        if (dumpState.onTitlePrinted())
22524                            pw.println();
22525                        pw.println("Intent Filter Verifier:");
22526                        pw.print("  Using: ");
22527                        pw.print(verifierPackageName);
22528                        pw.print(" (uid=");
22529                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22530                                UserHandle.USER_SYSTEM));
22531                        pw.println(")");
22532                    } else if (verifierPackageName != null) {
22533                        pw.print("ifv,"); pw.print(verifierPackageName);
22534                        pw.print(",");
22535                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22536                                UserHandle.USER_SYSTEM));
22537                    }
22538                } else {
22539                    pw.println();
22540                    pw.println("No Intent Filter Verifier available!");
22541                }
22542            }
22543
22544            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22545                boolean printedHeader = false;
22546                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22547                while (it.hasNext()) {
22548                    String libName = it.next();
22549                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22550                    if (versionedLib == null) {
22551                        continue;
22552                    }
22553                    final int versionCount = versionedLib.size();
22554                    for (int i = 0; i < versionCount; i++) {
22555                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22556                        if (!checkin) {
22557                            if (!printedHeader) {
22558                                if (dumpState.onTitlePrinted())
22559                                    pw.println();
22560                                pw.println("Libraries:");
22561                                printedHeader = true;
22562                            }
22563                            pw.print("  ");
22564                        } else {
22565                            pw.print("lib,");
22566                        }
22567                        pw.print(libEntry.info.getName());
22568                        if (libEntry.info.isStatic()) {
22569                            pw.print(" version=" + libEntry.info.getVersion());
22570                        }
22571                        if (!checkin) {
22572                            pw.print(" -> ");
22573                        }
22574                        if (libEntry.path != null) {
22575                            pw.print(" (jar) ");
22576                            pw.print(libEntry.path);
22577                        } else {
22578                            pw.print(" (apk) ");
22579                            pw.print(libEntry.apk);
22580                        }
22581                        pw.println();
22582                    }
22583                }
22584            }
22585
22586            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22587                if (dumpState.onTitlePrinted())
22588                    pw.println();
22589                if (!checkin) {
22590                    pw.println("Features:");
22591                }
22592
22593                synchronized (mAvailableFeatures) {
22594                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22595                        if (checkin) {
22596                            pw.print("feat,");
22597                            pw.print(feat.name);
22598                            pw.print(",");
22599                            pw.println(feat.version);
22600                        } else {
22601                            pw.print("  ");
22602                            pw.print(feat.name);
22603                            if (feat.version > 0) {
22604                                pw.print(" version=");
22605                                pw.print(feat.version);
22606                            }
22607                            pw.println();
22608                        }
22609                    }
22610                }
22611            }
22612
22613            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22614                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22615                        : "Activity Resolver Table:", "  ", packageName,
22616                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22617                    dumpState.setTitlePrinted(true);
22618                }
22619            }
22620            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22621                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22622                        : "Receiver Resolver Table:", "  ", packageName,
22623                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22624                    dumpState.setTitlePrinted(true);
22625                }
22626            }
22627            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22628                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22629                        : "Service Resolver Table:", "  ", packageName,
22630                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22631                    dumpState.setTitlePrinted(true);
22632                }
22633            }
22634            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22635                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22636                        : "Provider Resolver Table:", "  ", packageName,
22637                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22638                    dumpState.setTitlePrinted(true);
22639                }
22640            }
22641
22642            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22643                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22644                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22645                    int user = mSettings.mPreferredActivities.keyAt(i);
22646                    if (pir.dump(pw,
22647                            dumpState.getTitlePrinted()
22648                                ? "\nPreferred Activities User " + user + ":"
22649                                : "Preferred Activities User " + user + ":", "  ",
22650                            packageName, true, false)) {
22651                        dumpState.setTitlePrinted(true);
22652                    }
22653                }
22654            }
22655
22656            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22657                pw.flush();
22658                FileOutputStream fout = new FileOutputStream(fd);
22659                BufferedOutputStream str = new BufferedOutputStream(fout);
22660                XmlSerializer serializer = new FastXmlSerializer();
22661                try {
22662                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22663                    serializer.startDocument(null, true);
22664                    serializer.setFeature(
22665                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22666                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22667                    serializer.endDocument();
22668                    serializer.flush();
22669                } catch (IllegalArgumentException e) {
22670                    pw.println("Failed writing: " + e);
22671                } catch (IllegalStateException e) {
22672                    pw.println("Failed writing: " + e);
22673                } catch (IOException e) {
22674                    pw.println("Failed writing: " + e);
22675                }
22676            }
22677
22678            if (!checkin
22679                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22680                    && packageName == null) {
22681                pw.println();
22682                int count = mSettings.mPackages.size();
22683                if (count == 0) {
22684                    pw.println("No applications!");
22685                    pw.println();
22686                } else {
22687                    final String prefix = "  ";
22688                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22689                    if (allPackageSettings.size() == 0) {
22690                        pw.println("No domain preferred apps!");
22691                        pw.println();
22692                    } else {
22693                        pw.println("App verification status:");
22694                        pw.println();
22695                        count = 0;
22696                        for (PackageSetting ps : allPackageSettings) {
22697                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22698                            if (ivi == null || ivi.getPackageName() == null) continue;
22699                            pw.println(prefix + "Package: " + ivi.getPackageName());
22700                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22701                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22702                            pw.println();
22703                            count++;
22704                        }
22705                        if (count == 0) {
22706                            pw.println(prefix + "No app verification established.");
22707                            pw.println();
22708                        }
22709                        for (int userId : sUserManager.getUserIds()) {
22710                            pw.println("App linkages for user " + userId + ":");
22711                            pw.println();
22712                            count = 0;
22713                            for (PackageSetting ps : allPackageSettings) {
22714                                final long status = ps.getDomainVerificationStatusForUser(userId);
22715                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22716                                        && !DEBUG_DOMAIN_VERIFICATION) {
22717                                    continue;
22718                                }
22719                                pw.println(prefix + "Package: " + ps.name);
22720                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22721                                String statusStr = IntentFilterVerificationInfo.
22722                                        getStatusStringFromValue(status);
22723                                pw.println(prefix + "Status:  " + statusStr);
22724                                pw.println();
22725                                count++;
22726                            }
22727                            if (count == 0) {
22728                                pw.println(prefix + "No configured app linkages.");
22729                                pw.println();
22730                            }
22731                        }
22732                    }
22733                }
22734            }
22735
22736            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22737                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22738                if (packageName == null && permissionNames == null) {
22739                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22740                        if (iperm == 0) {
22741                            if (dumpState.onTitlePrinted())
22742                                pw.println();
22743                            pw.println("AppOp Permissions:");
22744                        }
22745                        pw.print("  AppOp Permission ");
22746                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22747                        pw.println(":");
22748                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22749                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22750                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22751                        }
22752                    }
22753                }
22754            }
22755
22756            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22757                boolean printedSomething = false;
22758                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22759                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22760                        continue;
22761                    }
22762                    if (!printedSomething) {
22763                        if (dumpState.onTitlePrinted())
22764                            pw.println();
22765                        pw.println("Registered ContentProviders:");
22766                        printedSomething = true;
22767                    }
22768                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22769                    pw.print("    "); pw.println(p.toString());
22770                }
22771                printedSomething = false;
22772                for (Map.Entry<String, PackageParser.Provider> entry :
22773                        mProvidersByAuthority.entrySet()) {
22774                    PackageParser.Provider p = entry.getValue();
22775                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22776                        continue;
22777                    }
22778                    if (!printedSomething) {
22779                        if (dumpState.onTitlePrinted())
22780                            pw.println();
22781                        pw.println("ContentProvider Authorities:");
22782                        printedSomething = true;
22783                    }
22784                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22785                    pw.print("    "); pw.println(p.toString());
22786                    if (p.info != null && p.info.applicationInfo != null) {
22787                        final String appInfo = p.info.applicationInfo.toString();
22788                        pw.print("      applicationInfo="); pw.println(appInfo);
22789                    }
22790                }
22791            }
22792
22793            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22794                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22795            }
22796
22797            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22798                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22799            }
22800
22801            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22802                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22803            }
22804
22805            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22806                if (dumpState.onTitlePrinted()) pw.println();
22807                pw.println("Package Changes:");
22808                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22809                final int K = mChangedPackages.size();
22810                for (int i = 0; i < K; i++) {
22811                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22812                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22813                    final int N = changes.size();
22814                    if (N == 0) {
22815                        pw.print("    "); pw.println("No packages changed");
22816                    } else {
22817                        for (int j = 0; j < N; j++) {
22818                            final String pkgName = changes.valueAt(j);
22819                            final int sequenceNumber = changes.keyAt(j);
22820                            pw.print("    ");
22821                            pw.print("seq=");
22822                            pw.print(sequenceNumber);
22823                            pw.print(", package=");
22824                            pw.println(pkgName);
22825                        }
22826                    }
22827                }
22828            }
22829
22830            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22831                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22832            }
22833
22834            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22835                // XXX should handle packageName != null by dumping only install data that
22836                // the given package is involved with.
22837                if (dumpState.onTitlePrinted()) pw.println();
22838
22839                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22840                ipw.println();
22841                ipw.println("Frozen packages:");
22842                ipw.increaseIndent();
22843                if (mFrozenPackages.size() == 0) {
22844                    ipw.println("(none)");
22845                } else {
22846                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22847                        ipw.println(mFrozenPackages.valueAt(i));
22848                    }
22849                }
22850                ipw.decreaseIndent();
22851            }
22852
22853            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22854                if (dumpState.onTitlePrinted()) pw.println();
22855
22856                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22857                ipw.println();
22858                ipw.println("Loaded volumes:");
22859                ipw.increaseIndent();
22860                if (mLoadedVolumes.size() == 0) {
22861                    ipw.println("(none)");
22862                } else {
22863                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22864                        ipw.println(mLoadedVolumes.valueAt(i));
22865                    }
22866                }
22867                ipw.decreaseIndent();
22868            }
22869
22870            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22871                if (dumpState.onTitlePrinted()) pw.println();
22872                dumpDexoptStateLPr(pw, packageName);
22873            }
22874
22875            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22876                if (dumpState.onTitlePrinted()) pw.println();
22877                dumpCompilerStatsLPr(pw, packageName);
22878            }
22879
22880            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22881                if (dumpState.onTitlePrinted()) pw.println();
22882                mSettings.dumpReadMessagesLPr(pw, dumpState);
22883
22884                pw.println();
22885                pw.println("Package warning messages:");
22886                BufferedReader in = null;
22887                String line = null;
22888                try {
22889                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22890                    while ((line = in.readLine()) != null) {
22891                        if (line.contains("ignored: updated version")) continue;
22892                        pw.println(line);
22893                    }
22894                } catch (IOException ignored) {
22895                } finally {
22896                    IoUtils.closeQuietly(in);
22897                }
22898            }
22899
22900            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22901                BufferedReader in = null;
22902                String line = null;
22903                try {
22904                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22905                    while ((line = in.readLine()) != null) {
22906                        if (line.contains("ignored: updated version")) continue;
22907                        pw.print("msg,");
22908                        pw.println(line);
22909                    }
22910                } catch (IOException ignored) {
22911                } finally {
22912                    IoUtils.closeQuietly(in);
22913                }
22914            }
22915        }
22916
22917        // PackageInstaller should be called outside of mPackages lock
22918        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22919            // XXX should handle packageName != null by dumping only install data that
22920            // the given package is involved with.
22921            if (dumpState.onTitlePrinted()) pw.println();
22922            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22923        }
22924    }
22925
22926    private void dumpProto(FileDescriptor fd) {
22927        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22928
22929        synchronized (mPackages) {
22930            final long requiredVerifierPackageToken =
22931                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22932            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22933            proto.write(
22934                    PackageServiceDumpProto.PackageShortProto.UID,
22935                    getPackageUid(
22936                            mRequiredVerifierPackage,
22937                            MATCH_DEBUG_TRIAGED_MISSING,
22938                            UserHandle.USER_SYSTEM));
22939            proto.end(requiredVerifierPackageToken);
22940
22941            if (mIntentFilterVerifierComponent != null) {
22942                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22943                final long verifierPackageToken =
22944                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22945                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22946                proto.write(
22947                        PackageServiceDumpProto.PackageShortProto.UID,
22948                        getPackageUid(
22949                                verifierPackageName,
22950                                MATCH_DEBUG_TRIAGED_MISSING,
22951                                UserHandle.USER_SYSTEM));
22952                proto.end(verifierPackageToken);
22953            }
22954
22955            dumpSharedLibrariesProto(proto);
22956            dumpFeaturesProto(proto);
22957            mSettings.dumpPackagesProto(proto);
22958            mSettings.dumpSharedUsersProto(proto);
22959            dumpMessagesProto(proto);
22960        }
22961        proto.flush();
22962    }
22963
22964    private void dumpMessagesProto(ProtoOutputStream proto) {
22965        BufferedReader in = null;
22966        String line = null;
22967        try {
22968            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22969            while ((line = in.readLine()) != null) {
22970                if (line.contains("ignored: updated version")) continue;
22971                proto.write(PackageServiceDumpProto.MESSAGES, line);
22972            }
22973        } catch (IOException ignored) {
22974        } finally {
22975            IoUtils.closeQuietly(in);
22976        }
22977    }
22978
22979    private void dumpFeaturesProto(ProtoOutputStream proto) {
22980        synchronized (mAvailableFeatures) {
22981            final int count = mAvailableFeatures.size();
22982            for (int i = 0; i < count; i++) {
22983                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22984                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22985                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22986                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22987                proto.end(featureToken);
22988            }
22989        }
22990    }
22991
22992    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22993        final int count = mSharedLibraries.size();
22994        for (int i = 0; i < count; i++) {
22995            final String libName = mSharedLibraries.keyAt(i);
22996            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22997            if (versionedLib == null) {
22998                continue;
22999            }
23000            final int versionCount = versionedLib.size();
23001            for (int j = 0; j < versionCount; j++) {
23002                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23003                final long sharedLibraryToken =
23004                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23005                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23006                final boolean isJar = (libEntry.path != null);
23007                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23008                if (isJar) {
23009                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23010                } else {
23011                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23012                }
23013                proto.end(sharedLibraryToken);
23014            }
23015        }
23016    }
23017
23018    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23019        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23020        ipw.println();
23021        ipw.println("Dexopt state:");
23022        ipw.increaseIndent();
23023        Collection<PackageParser.Package> packages = null;
23024        if (packageName != null) {
23025            PackageParser.Package targetPackage = mPackages.get(packageName);
23026            if (targetPackage != null) {
23027                packages = Collections.singletonList(targetPackage);
23028            } else {
23029                ipw.println("Unable to find package: " + packageName);
23030                return;
23031            }
23032        } else {
23033            packages = mPackages.values();
23034        }
23035
23036        for (PackageParser.Package pkg : packages) {
23037            ipw.println("[" + pkg.packageName + "]");
23038            ipw.increaseIndent();
23039            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23040                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23041            ipw.decreaseIndent();
23042        }
23043    }
23044
23045    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23046        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23047        ipw.println();
23048        ipw.println("Compiler stats:");
23049        ipw.increaseIndent();
23050        Collection<PackageParser.Package> packages = null;
23051        if (packageName != null) {
23052            PackageParser.Package targetPackage = mPackages.get(packageName);
23053            if (targetPackage != null) {
23054                packages = Collections.singletonList(targetPackage);
23055            } else {
23056                ipw.println("Unable to find package: " + packageName);
23057                return;
23058            }
23059        } else {
23060            packages = mPackages.values();
23061        }
23062
23063        for (PackageParser.Package pkg : packages) {
23064            ipw.println("[" + pkg.packageName + "]");
23065            ipw.increaseIndent();
23066
23067            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23068            if (stats == null) {
23069                ipw.println("(No recorded stats)");
23070            } else {
23071                stats.dump(ipw);
23072            }
23073            ipw.decreaseIndent();
23074        }
23075    }
23076
23077    private String dumpDomainString(String packageName) {
23078        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23079                .getList();
23080        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23081
23082        ArraySet<String> result = new ArraySet<>();
23083        if (iviList.size() > 0) {
23084            for (IntentFilterVerificationInfo ivi : iviList) {
23085                for (String host : ivi.getDomains()) {
23086                    result.add(host);
23087                }
23088            }
23089        }
23090        if (filters != null && filters.size() > 0) {
23091            for (IntentFilter filter : filters) {
23092                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23093                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23094                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23095                    result.addAll(filter.getHostsList());
23096                }
23097            }
23098        }
23099
23100        StringBuilder sb = new StringBuilder(result.size() * 16);
23101        for (String domain : result) {
23102            if (sb.length() > 0) sb.append(" ");
23103            sb.append(domain);
23104        }
23105        return sb.toString();
23106    }
23107
23108    // ------- apps on sdcard specific code -------
23109    static final boolean DEBUG_SD_INSTALL = false;
23110
23111    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23112
23113    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23114
23115    private boolean mMediaMounted = false;
23116
23117    static String getEncryptKey() {
23118        try {
23119            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23120                    SD_ENCRYPTION_KEYSTORE_NAME);
23121            if (sdEncKey == null) {
23122                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23123                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23124                if (sdEncKey == null) {
23125                    Slog.e(TAG, "Failed to create encryption keys");
23126                    return null;
23127                }
23128            }
23129            return sdEncKey;
23130        } catch (NoSuchAlgorithmException nsae) {
23131            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23132            return null;
23133        } catch (IOException ioe) {
23134            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23135            return null;
23136        }
23137    }
23138
23139    /*
23140     * Update media status on PackageManager.
23141     */
23142    @Override
23143    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23144        enforceSystemOrRoot("Media status can only be updated by the system");
23145        // reader; this apparently protects mMediaMounted, but should probably
23146        // be a different lock in that case.
23147        synchronized (mPackages) {
23148            Log.i(TAG, "Updating external media status from "
23149                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23150                    + (mediaStatus ? "mounted" : "unmounted"));
23151            if (DEBUG_SD_INSTALL)
23152                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23153                        + ", mMediaMounted=" + mMediaMounted);
23154            if (mediaStatus == mMediaMounted) {
23155                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23156                        : 0, -1);
23157                mHandler.sendMessage(msg);
23158                return;
23159            }
23160            mMediaMounted = mediaStatus;
23161        }
23162        // Queue up an async operation since the package installation may take a
23163        // little while.
23164        mHandler.post(new Runnable() {
23165            public void run() {
23166                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23167            }
23168        });
23169    }
23170
23171    /**
23172     * Called by StorageManagerService when the initial ASECs to scan are available.
23173     * Should block until all the ASEC containers are finished being scanned.
23174     */
23175    public void scanAvailableAsecs() {
23176        updateExternalMediaStatusInner(true, false, false);
23177    }
23178
23179    /*
23180     * Collect information of applications on external media, map them against
23181     * existing containers and update information based on current mount status.
23182     * Please note that we always have to report status if reportStatus has been
23183     * set to true especially when unloading packages.
23184     */
23185    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23186            boolean externalStorage) {
23187        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23188        int[] uidArr = EmptyArray.INT;
23189
23190        final String[] list = PackageHelper.getSecureContainerList();
23191        if (ArrayUtils.isEmpty(list)) {
23192            Log.i(TAG, "No secure containers found");
23193        } else {
23194            // Process list of secure containers and categorize them
23195            // as active or stale based on their package internal state.
23196
23197            // reader
23198            synchronized (mPackages) {
23199                for (String cid : list) {
23200                    // Leave stages untouched for now; installer service owns them
23201                    if (PackageInstallerService.isStageName(cid)) continue;
23202
23203                    if (DEBUG_SD_INSTALL)
23204                        Log.i(TAG, "Processing container " + cid);
23205                    String pkgName = getAsecPackageName(cid);
23206                    if (pkgName == null) {
23207                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23208                        continue;
23209                    }
23210                    if (DEBUG_SD_INSTALL)
23211                        Log.i(TAG, "Looking for pkg : " + pkgName);
23212
23213                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23214                    if (ps == null) {
23215                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23216                        continue;
23217                    }
23218
23219                    /*
23220                     * Skip packages that are not external if we're unmounting
23221                     * external storage.
23222                     */
23223                    if (externalStorage && !isMounted && !isExternal(ps)) {
23224                        continue;
23225                    }
23226
23227                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23228                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23229                    // The package status is changed only if the code path
23230                    // matches between settings and the container id.
23231                    if (ps.codePathString != null
23232                            && ps.codePathString.startsWith(args.getCodePath())) {
23233                        if (DEBUG_SD_INSTALL) {
23234                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23235                                    + " at code path: " + ps.codePathString);
23236                        }
23237
23238                        // We do have a valid package installed on sdcard
23239                        processCids.put(args, ps.codePathString);
23240                        final int uid = ps.appId;
23241                        if (uid != -1) {
23242                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23243                        }
23244                    } else {
23245                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23246                                + ps.codePathString);
23247                    }
23248                }
23249            }
23250
23251            Arrays.sort(uidArr);
23252        }
23253
23254        // Process packages with valid entries.
23255        if (isMounted) {
23256            if (DEBUG_SD_INSTALL)
23257                Log.i(TAG, "Loading packages");
23258            loadMediaPackages(processCids, uidArr, externalStorage);
23259            startCleaningPackages();
23260            mInstallerService.onSecureContainersAvailable();
23261        } else {
23262            if (DEBUG_SD_INSTALL)
23263                Log.i(TAG, "Unloading packages");
23264            unloadMediaPackages(processCids, uidArr, reportStatus);
23265        }
23266    }
23267
23268    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23269            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23270        final int size = infos.size();
23271        final String[] packageNames = new String[size];
23272        final int[] packageUids = new int[size];
23273        for (int i = 0; i < size; i++) {
23274            final ApplicationInfo info = infos.get(i);
23275            packageNames[i] = info.packageName;
23276            packageUids[i] = info.uid;
23277        }
23278        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23279                finishedReceiver);
23280    }
23281
23282    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23283            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23284        sendResourcesChangedBroadcast(mediaStatus, replacing,
23285                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23286    }
23287
23288    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23289            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23290        int size = pkgList.length;
23291        if (size > 0) {
23292            // Send broadcasts here
23293            Bundle extras = new Bundle();
23294            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23295            if (uidArr != null) {
23296                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23297            }
23298            if (replacing) {
23299                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23300            }
23301            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23302                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23303            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23304        }
23305    }
23306
23307   /*
23308     * Look at potentially valid container ids from processCids If package
23309     * information doesn't match the one on record or package scanning fails,
23310     * the cid is added to list of removeCids. We currently don't delete stale
23311     * containers.
23312     */
23313    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23314            boolean externalStorage) {
23315        ArrayList<String> pkgList = new ArrayList<String>();
23316        Set<AsecInstallArgs> keys = processCids.keySet();
23317
23318        for (AsecInstallArgs args : keys) {
23319            String codePath = processCids.get(args);
23320            if (DEBUG_SD_INSTALL)
23321                Log.i(TAG, "Loading container : " + args.cid);
23322            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23323            try {
23324                // Make sure there are no container errors first.
23325                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23326                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23327                            + " when installing from sdcard");
23328                    continue;
23329                }
23330                // Check code path here.
23331                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23332                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23333                            + " does not match one in settings " + codePath);
23334                    continue;
23335                }
23336                // Parse package
23337                int parseFlags = mDefParseFlags;
23338                if (args.isExternalAsec()) {
23339                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23340                }
23341                if (args.isFwdLocked()) {
23342                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23343                }
23344
23345                synchronized (mInstallLock) {
23346                    PackageParser.Package pkg = null;
23347                    try {
23348                        // Sadly we don't know the package name yet to freeze it
23349                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23350                                SCAN_IGNORE_FROZEN, 0, null);
23351                    } catch (PackageManagerException e) {
23352                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23353                    }
23354                    // Scan the package
23355                    if (pkg != null) {
23356                        /*
23357                         * TODO why is the lock being held? doPostInstall is
23358                         * called in other places without the lock. This needs
23359                         * to be straightened out.
23360                         */
23361                        // writer
23362                        synchronized (mPackages) {
23363                            retCode = PackageManager.INSTALL_SUCCEEDED;
23364                            pkgList.add(pkg.packageName);
23365                            // Post process args
23366                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23367                                    pkg.applicationInfo.uid);
23368                        }
23369                    } else {
23370                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23371                    }
23372                }
23373
23374            } finally {
23375                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23376                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23377                }
23378            }
23379        }
23380        // writer
23381        synchronized (mPackages) {
23382            // If the platform SDK has changed since the last time we booted,
23383            // we need to re-grant app permission to catch any new ones that
23384            // appear. This is really a hack, and means that apps can in some
23385            // cases get permissions that the user didn't initially explicitly
23386            // allow... it would be nice to have some better way to handle
23387            // this situation.
23388            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23389                    : mSettings.getInternalVersion();
23390            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23391                    : StorageManager.UUID_PRIVATE_INTERNAL;
23392
23393            int updateFlags = UPDATE_PERMISSIONS_ALL;
23394            if (ver.sdkVersion != mSdkVersion) {
23395                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23396                        + mSdkVersion + "; regranting permissions for external");
23397                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23398            }
23399            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23400
23401            // Yay, everything is now upgraded
23402            ver.forceCurrent();
23403
23404            // can downgrade to reader
23405            // Persist settings
23406            mSettings.writeLPr();
23407        }
23408        // Send a broadcast to let everyone know we are done processing
23409        if (pkgList.size() > 0) {
23410            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23411        }
23412    }
23413
23414   /*
23415     * Utility method to unload a list of specified containers
23416     */
23417    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23418        // Just unmount all valid containers.
23419        for (AsecInstallArgs arg : cidArgs) {
23420            synchronized (mInstallLock) {
23421                arg.doPostDeleteLI(false);
23422           }
23423       }
23424   }
23425
23426    /*
23427     * Unload packages mounted on external media. This involves deleting package
23428     * data from internal structures, sending broadcasts about disabled packages,
23429     * gc'ing to free up references, unmounting all secure containers
23430     * corresponding to packages on external media, and posting a
23431     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23432     * that we always have to post this message if status has been requested no
23433     * matter what.
23434     */
23435    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23436            final boolean reportStatus) {
23437        if (DEBUG_SD_INSTALL)
23438            Log.i(TAG, "unloading media packages");
23439        ArrayList<String> pkgList = new ArrayList<String>();
23440        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23441        final Set<AsecInstallArgs> keys = processCids.keySet();
23442        for (AsecInstallArgs args : keys) {
23443            String pkgName = args.getPackageName();
23444            if (DEBUG_SD_INSTALL)
23445                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23446            // Delete package internally
23447            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23448            synchronized (mInstallLock) {
23449                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23450                final boolean res;
23451                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23452                        "unloadMediaPackages")) {
23453                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23454                            null);
23455                }
23456                if (res) {
23457                    pkgList.add(pkgName);
23458                } else {
23459                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23460                    failedList.add(args);
23461                }
23462            }
23463        }
23464
23465        // reader
23466        synchronized (mPackages) {
23467            // We didn't update the settings after removing each package;
23468            // write them now for all packages.
23469            mSettings.writeLPr();
23470        }
23471
23472        // We have to absolutely send UPDATED_MEDIA_STATUS only
23473        // after confirming that all the receivers processed the ordered
23474        // broadcast when packages get disabled, force a gc to clean things up.
23475        // and unload all the containers.
23476        if (pkgList.size() > 0) {
23477            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23478                    new IIntentReceiver.Stub() {
23479                public void performReceive(Intent intent, int resultCode, String data,
23480                        Bundle extras, boolean ordered, boolean sticky,
23481                        int sendingUser) throws RemoteException {
23482                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23483                            reportStatus ? 1 : 0, 1, keys);
23484                    mHandler.sendMessage(msg);
23485                }
23486            });
23487        } else {
23488            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23489                    keys);
23490            mHandler.sendMessage(msg);
23491        }
23492    }
23493
23494    private void loadPrivatePackages(final VolumeInfo vol) {
23495        mHandler.post(new Runnable() {
23496            @Override
23497            public void run() {
23498                loadPrivatePackagesInner(vol);
23499            }
23500        });
23501    }
23502
23503    private void loadPrivatePackagesInner(VolumeInfo vol) {
23504        final String volumeUuid = vol.fsUuid;
23505        if (TextUtils.isEmpty(volumeUuid)) {
23506            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23507            return;
23508        }
23509
23510        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23511        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23512        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23513
23514        final VersionInfo ver;
23515        final List<PackageSetting> packages;
23516        synchronized (mPackages) {
23517            ver = mSettings.findOrCreateVersion(volumeUuid);
23518            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23519        }
23520
23521        for (PackageSetting ps : packages) {
23522            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23523            synchronized (mInstallLock) {
23524                final PackageParser.Package pkg;
23525                try {
23526                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23527                    loaded.add(pkg.applicationInfo);
23528
23529                } catch (PackageManagerException e) {
23530                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23531                }
23532
23533                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23534                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23535                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23536                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23537                }
23538            }
23539        }
23540
23541        // Reconcile app data for all started/unlocked users
23542        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23543        final UserManager um = mContext.getSystemService(UserManager.class);
23544        UserManagerInternal umInternal = getUserManagerInternal();
23545        for (UserInfo user : um.getUsers()) {
23546            final int flags;
23547            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23548                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23549            } else if (umInternal.isUserRunning(user.id)) {
23550                flags = StorageManager.FLAG_STORAGE_DE;
23551            } else {
23552                continue;
23553            }
23554
23555            try {
23556                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23557                synchronized (mInstallLock) {
23558                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23559                }
23560            } catch (IllegalStateException e) {
23561                // Device was probably ejected, and we'll process that event momentarily
23562                Slog.w(TAG, "Failed to prepare storage: " + e);
23563            }
23564        }
23565
23566        synchronized (mPackages) {
23567            int updateFlags = UPDATE_PERMISSIONS_ALL;
23568            if (ver.sdkVersion != mSdkVersion) {
23569                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23570                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23571                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23572            }
23573            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23574
23575            // Yay, everything is now upgraded
23576            ver.forceCurrent();
23577
23578            mSettings.writeLPr();
23579        }
23580
23581        for (PackageFreezer freezer : freezers) {
23582            freezer.close();
23583        }
23584
23585        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23586        sendResourcesChangedBroadcast(true, false, loaded, null);
23587        mLoadedVolumes.add(vol.getId());
23588    }
23589
23590    private void unloadPrivatePackages(final VolumeInfo vol) {
23591        mHandler.post(new Runnable() {
23592            @Override
23593            public void run() {
23594                unloadPrivatePackagesInner(vol);
23595            }
23596        });
23597    }
23598
23599    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23600        final String volumeUuid = vol.fsUuid;
23601        if (TextUtils.isEmpty(volumeUuid)) {
23602            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23603            return;
23604        }
23605
23606        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23607        synchronized (mInstallLock) {
23608        synchronized (mPackages) {
23609            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23610            for (PackageSetting ps : packages) {
23611                if (ps.pkg == null) continue;
23612
23613                final ApplicationInfo info = ps.pkg.applicationInfo;
23614                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23615                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23616
23617                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23618                        "unloadPrivatePackagesInner")) {
23619                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23620                            false, null)) {
23621                        unloaded.add(info);
23622                    } else {
23623                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23624                    }
23625                }
23626
23627                // Try very hard to release any references to this package
23628                // so we don't risk the system server being killed due to
23629                // open FDs
23630                AttributeCache.instance().removePackage(ps.name);
23631            }
23632
23633            mSettings.writeLPr();
23634        }
23635        }
23636
23637        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23638        sendResourcesChangedBroadcast(false, false, unloaded, null);
23639        mLoadedVolumes.remove(vol.getId());
23640
23641        // Try very hard to release any references to this path so we don't risk
23642        // the system server being killed due to open FDs
23643        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23644
23645        for (int i = 0; i < 3; i++) {
23646            System.gc();
23647            System.runFinalization();
23648        }
23649    }
23650
23651    private void assertPackageKnown(String volumeUuid, String packageName)
23652            throws PackageManagerException {
23653        synchronized (mPackages) {
23654            // Normalize package name to handle renamed packages
23655            packageName = normalizePackageNameLPr(packageName);
23656
23657            final PackageSetting ps = mSettings.mPackages.get(packageName);
23658            if (ps == null) {
23659                throw new PackageManagerException("Package " + packageName + " is unknown");
23660            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23661                throw new PackageManagerException(
23662                        "Package " + packageName + " found on unknown volume " + volumeUuid
23663                                + "; expected volume " + ps.volumeUuid);
23664            }
23665        }
23666    }
23667
23668    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23669            throws PackageManagerException {
23670        synchronized (mPackages) {
23671            // Normalize package name to handle renamed packages
23672            packageName = normalizePackageNameLPr(packageName);
23673
23674            final PackageSetting ps = mSettings.mPackages.get(packageName);
23675            if (ps == null) {
23676                throw new PackageManagerException("Package " + packageName + " is unknown");
23677            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23678                throw new PackageManagerException(
23679                        "Package " + packageName + " found on unknown volume " + volumeUuid
23680                                + "; expected volume " + ps.volumeUuid);
23681            } else if (!ps.getInstalled(userId)) {
23682                throw new PackageManagerException(
23683                        "Package " + packageName + " not installed for user " + userId);
23684            }
23685        }
23686    }
23687
23688    private List<String> collectAbsoluteCodePaths() {
23689        synchronized (mPackages) {
23690            List<String> codePaths = new ArrayList<>();
23691            final int packageCount = mSettings.mPackages.size();
23692            for (int i = 0; i < packageCount; i++) {
23693                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23694                codePaths.add(ps.codePath.getAbsolutePath());
23695            }
23696            return codePaths;
23697        }
23698    }
23699
23700    /**
23701     * Examine all apps present on given mounted volume, and destroy apps that
23702     * aren't expected, either due to uninstallation or reinstallation on
23703     * another volume.
23704     */
23705    private void reconcileApps(String volumeUuid) {
23706        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23707        List<File> filesToDelete = null;
23708
23709        final File[] files = FileUtils.listFilesOrEmpty(
23710                Environment.getDataAppDirectory(volumeUuid));
23711        for (File file : files) {
23712            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23713                    && !PackageInstallerService.isStageName(file.getName());
23714            if (!isPackage) {
23715                // Ignore entries which are not packages
23716                continue;
23717            }
23718
23719            String absolutePath = file.getAbsolutePath();
23720
23721            boolean pathValid = false;
23722            final int absoluteCodePathCount = absoluteCodePaths.size();
23723            for (int i = 0; i < absoluteCodePathCount; i++) {
23724                String absoluteCodePath = absoluteCodePaths.get(i);
23725                if (absolutePath.startsWith(absoluteCodePath)) {
23726                    pathValid = true;
23727                    break;
23728                }
23729            }
23730
23731            if (!pathValid) {
23732                if (filesToDelete == null) {
23733                    filesToDelete = new ArrayList<>();
23734                }
23735                filesToDelete.add(file);
23736            }
23737        }
23738
23739        if (filesToDelete != null) {
23740            final int fileToDeleteCount = filesToDelete.size();
23741            for (int i = 0; i < fileToDeleteCount; i++) {
23742                File fileToDelete = filesToDelete.get(i);
23743                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23744                synchronized (mInstallLock) {
23745                    removeCodePathLI(fileToDelete);
23746                }
23747            }
23748        }
23749    }
23750
23751    /**
23752     * Reconcile all app data for the given user.
23753     * <p>
23754     * Verifies that directories exist and that ownership and labeling is
23755     * correct for all installed apps on all mounted volumes.
23756     */
23757    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23758        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23759        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23760            final String volumeUuid = vol.getFsUuid();
23761            synchronized (mInstallLock) {
23762                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23763            }
23764        }
23765    }
23766
23767    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23768            boolean migrateAppData) {
23769        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23770    }
23771
23772    /**
23773     * Reconcile all app data on given mounted volume.
23774     * <p>
23775     * Destroys app data that isn't expected, either due to uninstallation or
23776     * reinstallation on another volume.
23777     * <p>
23778     * Verifies that directories exist and that ownership and labeling is
23779     * correct for all installed apps.
23780     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23781     */
23782    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23783            boolean migrateAppData, boolean onlyCoreApps) {
23784        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23785                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23786        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23787
23788        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23789        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23790
23791        // First look for stale data that doesn't belong, and check if things
23792        // have changed since we did our last restorecon
23793        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23794            if (StorageManager.isFileEncryptedNativeOrEmulated()
23795                    && !StorageManager.isUserKeyUnlocked(userId)) {
23796                throw new RuntimeException(
23797                        "Yikes, someone asked us to reconcile CE storage while " + userId
23798                                + " was still locked; this would have caused massive data loss!");
23799            }
23800
23801            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23802            for (File file : files) {
23803                final String packageName = file.getName();
23804                try {
23805                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23806                } catch (PackageManagerException e) {
23807                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23808                    try {
23809                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23810                                StorageManager.FLAG_STORAGE_CE, 0);
23811                    } catch (InstallerException e2) {
23812                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23813                    }
23814                }
23815            }
23816        }
23817        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23818            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23819            for (File file : files) {
23820                final String packageName = file.getName();
23821                try {
23822                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23823                } catch (PackageManagerException e) {
23824                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23825                    try {
23826                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23827                                StorageManager.FLAG_STORAGE_DE, 0);
23828                    } catch (InstallerException e2) {
23829                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23830                    }
23831                }
23832            }
23833        }
23834
23835        // Ensure that data directories are ready to roll for all packages
23836        // installed for this volume and user
23837        final List<PackageSetting> packages;
23838        synchronized (mPackages) {
23839            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23840        }
23841        int preparedCount = 0;
23842        for (PackageSetting ps : packages) {
23843            final String packageName = ps.name;
23844            if (ps.pkg == null) {
23845                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23846                // TODO: might be due to legacy ASEC apps; we should circle back
23847                // and reconcile again once they're scanned
23848                continue;
23849            }
23850            // Skip non-core apps if requested
23851            if (onlyCoreApps && !ps.pkg.coreApp) {
23852                result.add(packageName);
23853                continue;
23854            }
23855
23856            if (ps.getInstalled(userId)) {
23857                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23858                preparedCount++;
23859            }
23860        }
23861
23862        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23863        return result;
23864    }
23865
23866    /**
23867     * Prepare app data for the given app just after it was installed or
23868     * upgraded. This method carefully only touches users that it's installed
23869     * for, and it forces a restorecon to handle any seinfo changes.
23870     * <p>
23871     * Verifies that directories exist and that ownership and labeling is
23872     * correct for all installed apps. If there is an ownership mismatch, it
23873     * will try recovering system apps by wiping data; third-party app data is
23874     * left intact.
23875     * <p>
23876     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23877     */
23878    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23879        final PackageSetting ps;
23880        synchronized (mPackages) {
23881            ps = mSettings.mPackages.get(pkg.packageName);
23882            mSettings.writeKernelMappingLPr(ps);
23883        }
23884
23885        final UserManager um = mContext.getSystemService(UserManager.class);
23886        UserManagerInternal umInternal = getUserManagerInternal();
23887        for (UserInfo user : um.getUsers()) {
23888            final int flags;
23889            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23890                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23891            } else if (umInternal.isUserRunning(user.id)) {
23892                flags = StorageManager.FLAG_STORAGE_DE;
23893            } else {
23894                continue;
23895            }
23896
23897            if (ps.getInstalled(user.id)) {
23898                // TODO: when user data is locked, mark that we're still dirty
23899                prepareAppDataLIF(pkg, user.id, flags);
23900            }
23901        }
23902    }
23903
23904    /**
23905     * Prepare app data for the given app.
23906     * <p>
23907     * Verifies that directories exist and that ownership and labeling is
23908     * correct for all installed apps. If there is an ownership mismatch, this
23909     * will try recovering system apps by wiping data; third-party app data is
23910     * left intact.
23911     */
23912    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23913        if (pkg == null) {
23914            Slog.wtf(TAG, "Package was null!", new Throwable());
23915            return;
23916        }
23917        prepareAppDataLeafLIF(pkg, userId, flags);
23918        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23919        for (int i = 0; i < childCount; i++) {
23920            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23921        }
23922    }
23923
23924    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23925            boolean maybeMigrateAppData) {
23926        prepareAppDataLIF(pkg, userId, flags);
23927
23928        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23929            // We may have just shuffled around app data directories, so
23930            // prepare them one more time
23931            prepareAppDataLIF(pkg, userId, flags);
23932        }
23933    }
23934
23935    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23936        if (DEBUG_APP_DATA) {
23937            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23938                    + Integer.toHexString(flags));
23939        }
23940
23941        final String volumeUuid = pkg.volumeUuid;
23942        final String packageName = pkg.packageName;
23943        final ApplicationInfo app = pkg.applicationInfo;
23944        final int appId = UserHandle.getAppId(app.uid);
23945
23946        Preconditions.checkNotNull(app.seInfo);
23947
23948        long ceDataInode = -1;
23949        try {
23950            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23951                    appId, app.seInfo, app.targetSdkVersion);
23952        } catch (InstallerException e) {
23953            if (app.isSystemApp()) {
23954                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23955                        + ", but trying to recover: " + e);
23956                destroyAppDataLeafLIF(pkg, userId, flags);
23957                try {
23958                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23959                            appId, app.seInfo, app.targetSdkVersion);
23960                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23961                } catch (InstallerException e2) {
23962                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23963                }
23964            } else {
23965                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23966            }
23967        }
23968
23969        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23970            // TODO: mark this structure as dirty so we persist it!
23971            synchronized (mPackages) {
23972                final PackageSetting ps = mSettings.mPackages.get(packageName);
23973                if (ps != null) {
23974                    ps.setCeDataInode(ceDataInode, userId);
23975                }
23976            }
23977        }
23978
23979        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23980    }
23981
23982    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23983        if (pkg == null) {
23984            Slog.wtf(TAG, "Package was null!", new Throwable());
23985            return;
23986        }
23987        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23988        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23989        for (int i = 0; i < childCount; i++) {
23990            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23991        }
23992    }
23993
23994    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23995        final String volumeUuid = pkg.volumeUuid;
23996        final String packageName = pkg.packageName;
23997        final ApplicationInfo app = pkg.applicationInfo;
23998
23999        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24000            // Create a native library symlink only if we have native libraries
24001            // and if the native libraries are 32 bit libraries. We do not provide
24002            // this symlink for 64 bit libraries.
24003            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24004                final String nativeLibPath = app.nativeLibraryDir;
24005                try {
24006                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24007                            nativeLibPath, userId);
24008                } catch (InstallerException e) {
24009                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24010                }
24011            }
24012        }
24013    }
24014
24015    /**
24016     * For system apps on non-FBE devices, this method migrates any existing
24017     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24018     * requested by the app.
24019     */
24020    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24021        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24022                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24023            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24024                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24025            try {
24026                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24027                        storageTarget);
24028            } catch (InstallerException e) {
24029                logCriticalInfo(Log.WARN,
24030                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24031            }
24032            return true;
24033        } else {
24034            return false;
24035        }
24036    }
24037
24038    public PackageFreezer freezePackage(String packageName, String killReason) {
24039        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24040    }
24041
24042    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24043        return new PackageFreezer(packageName, userId, killReason);
24044    }
24045
24046    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24047            String killReason) {
24048        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24049    }
24050
24051    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24052            String killReason) {
24053        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24054            return new PackageFreezer();
24055        } else {
24056            return freezePackage(packageName, userId, killReason);
24057        }
24058    }
24059
24060    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24061            String killReason) {
24062        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24063    }
24064
24065    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24066            String killReason) {
24067        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24068            return new PackageFreezer();
24069        } else {
24070            return freezePackage(packageName, userId, killReason);
24071        }
24072    }
24073
24074    /**
24075     * Class that freezes and kills the given package upon creation, and
24076     * unfreezes it upon closing. This is typically used when doing surgery on
24077     * app code/data to prevent the app from running while you're working.
24078     */
24079    private class PackageFreezer implements AutoCloseable {
24080        private final String mPackageName;
24081        private final PackageFreezer[] mChildren;
24082
24083        private final boolean mWeFroze;
24084
24085        private final AtomicBoolean mClosed = new AtomicBoolean();
24086        private final CloseGuard mCloseGuard = CloseGuard.get();
24087
24088        /**
24089         * Create and return a stub freezer that doesn't actually do anything,
24090         * typically used when someone requested
24091         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24092         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24093         */
24094        public PackageFreezer() {
24095            mPackageName = null;
24096            mChildren = null;
24097            mWeFroze = false;
24098            mCloseGuard.open("close");
24099        }
24100
24101        public PackageFreezer(String packageName, int userId, String killReason) {
24102            synchronized (mPackages) {
24103                mPackageName = packageName;
24104                mWeFroze = mFrozenPackages.add(mPackageName);
24105
24106                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24107                if (ps != null) {
24108                    killApplication(ps.name, ps.appId, userId, killReason);
24109                }
24110
24111                final PackageParser.Package p = mPackages.get(packageName);
24112                if (p != null && p.childPackages != null) {
24113                    final int N = p.childPackages.size();
24114                    mChildren = new PackageFreezer[N];
24115                    for (int i = 0; i < N; i++) {
24116                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24117                                userId, killReason);
24118                    }
24119                } else {
24120                    mChildren = null;
24121                }
24122            }
24123            mCloseGuard.open("close");
24124        }
24125
24126        @Override
24127        protected void finalize() throws Throwable {
24128            try {
24129                if (mCloseGuard != null) {
24130                    mCloseGuard.warnIfOpen();
24131                }
24132
24133                close();
24134            } finally {
24135                super.finalize();
24136            }
24137        }
24138
24139        @Override
24140        public void close() {
24141            mCloseGuard.close();
24142            if (mClosed.compareAndSet(false, true)) {
24143                synchronized (mPackages) {
24144                    if (mWeFroze) {
24145                        mFrozenPackages.remove(mPackageName);
24146                    }
24147
24148                    if (mChildren != null) {
24149                        for (PackageFreezer freezer : mChildren) {
24150                            freezer.close();
24151                        }
24152                    }
24153                }
24154            }
24155        }
24156    }
24157
24158    /**
24159     * Verify that given package is currently frozen.
24160     */
24161    private void checkPackageFrozen(String packageName) {
24162        synchronized (mPackages) {
24163            if (!mFrozenPackages.contains(packageName)) {
24164                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24165            }
24166        }
24167    }
24168
24169    @Override
24170    public int movePackage(final String packageName, final String volumeUuid) {
24171        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24172
24173        final int callingUid = Binder.getCallingUid();
24174        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24175        final int moveId = mNextMoveId.getAndIncrement();
24176        mHandler.post(new Runnable() {
24177            @Override
24178            public void run() {
24179                try {
24180                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24181                } catch (PackageManagerException e) {
24182                    Slog.w(TAG, "Failed to move " + packageName, e);
24183                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24184                }
24185            }
24186        });
24187        return moveId;
24188    }
24189
24190    private void movePackageInternal(final String packageName, final String volumeUuid,
24191            final int moveId, final int callingUid, UserHandle user)
24192                    throws PackageManagerException {
24193        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24194        final PackageManager pm = mContext.getPackageManager();
24195
24196        final boolean currentAsec;
24197        final String currentVolumeUuid;
24198        final File codeFile;
24199        final String installerPackageName;
24200        final String packageAbiOverride;
24201        final int appId;
24202        final String seinfo;
24203        final String label;
24204        final int targetSdkVersion;
24205        final PackageFreezer freezer;
24206        final int[] installedUserIds;
24207
24208        // reader
24209        synchronized (mPackages) {
24210            final PackageParser.Package pkg = mPackages.get(packageName);
24211            final PackageSetting ps = mSettings.mPackages.get(packageName);
24212            if (pkg == null
24213                    || ps == null
24214                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24215                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24216            }
24217            if (pkg.applicationInfo.isSystemApp()) {
24218                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24219                        "Cannot move system application");
24220            }
24221
24222            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24223            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24224                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24225            if (isInternalStorage && !allow3rdPartyOnInternal) {
24226                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24227                        "3rd party apps are not allowed on internal storage");
24228            }
24229
24230            if (pkg.applicationInfo.isExternalAsec()) {
24231                currentAsec = true;
24232                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24233            } else if (pkg.applicationInfo.isForwardLocked()) {
24234                currentAsec = true;
24235                currentVolumeUuid = "forward_locked";
24236            } else {
24237                currentAsec = false;
24238                currentVolumeUuid = ps.volumeUuid;
24239
24240                final File probe = new File(pkg.codePath);
24241                final File probeOat = new File(probe, "oat");
24242                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24243                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24244                            "Move only supported for modern cluster style installs");
24245                }
24246            }
24247
24248            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24249                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24250                        "Package already moved to " + volumeUuid);
24251            }
24252            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24253                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24254                        "Device admin cannot be moved");
24255            }
24256
24257            if (mFrozenPackages.contains(packageName)) {
24258                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24259                        "Failed to move already frozen package");
24260            }
24261
24262            codeFile = new File(pkg.codePath);
24263            installerPackageName = ps.installerPackageName;
24264            packageAbiOverride = ps.cpuAbiOverrideString;
24265            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24266            seinfo = pkg.applicationInfo.seInfo;
24267            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24268            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24269            freezer = freezePackage(packageName, "movePackageInternal");
24270            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24271        }
24272
24273        final Bundle extras = new Bundle();
24274        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24275        extras.putString(Intent.EXTRA_TITLE, label);
24276        mMoveCallbacks.notifyCreated(moveId, extras);
24277
24278        int installFlags;
24279        final boolean moveCompleteApp;
24280        final File measurePath;
24281
24282        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24283            installFlags = INSTALL_INTERNAL;
24284            moveCompleteApp = !currentAsec;
24285            measurePath = Environment.getDataAppDirectory(volumeUuid);
24286        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24287            installFlags = INSTALL_EXTERNAL;
24288            moveCompleteApp = false;
24289            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24290        } else {
24291            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24292            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24293                    || !volume.isMountedWritable()) {
24294                freezer.close();
24295                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24296                        "Move location not mounted private volume");
24297            }
24298
24299            Preconditions.checkState(!currentAsec);
24300
24301            installFlags = INSTALL_INTERNAL;
24302            moveCompleteApp = true;
24303            measurePath = Environment.getDataAppDirectory(volumeUuid);
24304        }
24305
24306        // If we're moving app data around, we need all the users unlocked
24307        if (moveCompleteApp) {
24308            for (int userId : installedUserIds) {
24309                if (StorageManager.isFileEncryptedNativeOrEmulated()
24310                        && !StorageManager.isUserKeyUnlocked(userId)) {
24311                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24312                            "User " + userId + " must be unlocked");
24313                }
24314            }
24315        }
24316
24317        final PackageStats stats = new PackageStats(null, -1);
24318        synchronized (mInstaller) {
24319            for (int userId : installedUserIds) {
24320                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24321                    freezer.close();
24322                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24323                            "Failed to measure package size");
24324                }
24325            }
24326        }
24327
24328        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24329                + stats.dataSize);
24330
24331        final long startFreeBytes = measurePath.getUsableSpace();
24332        final long sizeBytes;
24333        if (moveCompleteApp) {
24334            sizeBytes = stats.codeSize + stats.dataSize;
24335        } else {
24336            sizeBytes = stats.codeSize;
24337        }
24338
24339        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24340            freezer.close();
24341            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24342                    "Not enough free space to move");
24343        }
24344
24345        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24346
24347        final CountDownLatch installedLatch = new CountDownLatch(1);
24348        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24349            @Override
24350            public void onUserActionRequired(Intent intent) throws RemoteException {
24351                throw new IllegalStateException();
24352            }
24353
24354            @Override
24355            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24356                    Bundle extras) throws RemoteException {
24357                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24358                        + PackageManager.installStatusToString(returnCode, msg));
24359
24360                installedLatch.countDown();
24361                freezer.close();
24362
24363                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24364                switch (status) {
24365                    case PackageInstaller.STATUS_SUCCESS:
24366                        mMoveCallbacks.notifyStatusChanged(moveId,
24367                                PackageManager.MOVE_SUCCEEDED);
24368                        break;
24369                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24370                        mMoveCallbacks.notifyStatusChanged(moveId,
24371                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24372                        break;
24373                    default:
24374                        mMoveCallbacks.notifyStatusChanged(moveId,
24375                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24376                        break;
24377                }
24378            }
24379        };
24380
24381        final MoveInfo move;
24382        if (moveCompleteApp) {
24383            // Kick off a thread to report progress estimates
24384            new Thread() {
24385                @Override
24386                public void run() {
24387                    while (true) {
24388                        try {
24389                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24390                                break;
24391                            }
24392                        } catch (InterruptedException ignored) {
24393                        }
24394
24395                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24396                        final int progress = 10 + (int) MathUtils.constrain(
24397                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24398                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24399                    }
24400                }
24401            }.start();
24402
24403            final String dataAppName = codeFile.getName();
24404            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24405                    dataAppName, appId, seinfo, targetSdkVersion);
24406        } else {
24407            move = null;
24408        }
24409
24410        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24411
24412        final Message msg = mHandler.obtainMessage(INIT_COPY);
24413        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24414        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24415                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24416                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24417                PackageManager.INSTALL_REASON_UNKNOWN);
24418        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24419        msg.obj = params;
24420
24421        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24422                System.identityHashCode(msg.obj));
24423        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24424                System.identityHashCode(msg.obj));
24425
24426        mHandler.sendMessage(msg);
24427    }
24428
24429    @Override
24430    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24431        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24432
24433        final int realMoveId = mNextMoveId.getAndIncrement();
24434        final Bundle extras = new Bundle();
24435        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24436        mMoveCallbacks.notifyCreated(realMoveId, extras);
24437
24438        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24439            @Override
24440            public void onCreated(int moveId, Bundle extras) {
24441                // Ignored
24442            }
24443
24444            @Override
24445            public void onStatusChanged(int moveId, int status, long estMillis) {
24446                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24447            }
24448        };
24449
24450        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24451        storage.setPrimaryStorageUuid(volumeUuid, callback);
24452        return realMoveId;
24453    }
24454
24455    @Override
24456    public int getMoveStatus(int moveId) {
24457        mContext.enforceCallingOrSelfPermission(
24458                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24459        return mMoveCallbacks.mLastStatus.get(moveId);
24460    }
24461
24462    @Override
24463    public void registerMoveCallback(IPackageMoveObserver callback) {
24464        mContext.enforceCallingOrSelfPermission(
24465                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24466        mMoveCallbacks.register(callback);
24467    }
24468
24469    @Override
24470    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24471        mContext.enforceCallingOrSelfPermission(
24472                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24473        mMoveCallbacks.unregister(callback);
24474    }
24475
24476    @Override
24477    public boolean setInstallLocation(int loc) {
24478        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24479                null);
24480        if (getInstallLocation() == loc) {
24481            return true;
24482        }
24483        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24484                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24485            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24486                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24487            return true;
24488        }
24489        return false;
24490   }
24491
24492    @Override
24493    public int getInstallLocation() {
24494        // allow instant app access
24495        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24496                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24497                PackageHelper.APP_INSTALL_AUTO);
24498    }
24499
24500    /** Called by UserManagerService */
24501    void cleanUpUser(UserManagerService userManager, int userHandle) {
24502        synchronized (mPackages) {
24503            mDirtyUsers.remove(userHandle);
24504            mUserNeedsBadging.delete(userHandle);
24505            mSettings.removeUserLPw(userHandle);
24506            mPendingBroadcasts.remove(userHandle);
24507            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24508            removeUnusedPackagesLPw(userManager, userHandle);
24509        }
24510    }
24511
24512    /**
24513     * We're removing userHandle and would like to remove any downloaded packages
24514     * that are no longer in use by any other user.
24515     * @param userHandle the user being removed
24516     */
24517    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24518        final boolean DEBUG_CLEAN_APKS = false;
24519        int [] users = userManager.getUserIds();
24520        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24521        while (psit.hasNext()) {
24522            PackageSetting ps = psit.next();
24523            if (ps.pkg == null) {
24524                continue;
24525            }
24526            final String packageName = ps.pkg.packageName;
24527            // Skip over if system app
24528            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24529                continue;
24530            }
24531            if (DEBUG_CLEAN_APKS) {
24532                Slog.i(TAG, "Checking package " + packageName);
24533            }
24534            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24535            if (keep) {
24536                if (DEBUG_CLEAN_APKS) {
24537                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24538                }
24539            } else {
24540                for (int i = 0; i < users.length; i++) {
24541                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24542                        keep = true;
24543                        if (DEBUG_CLEAN_APKS) {
24544                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24545                                    + users[i]);
24546                        }
24547                        break;
24548                    }
24549                }
24550            }
24551            if (!keep) {
24552                if (DEBUG_CLEAN_APKS) {
24553                    Slog.i(TAG, "  Removing package " + packageName);
24554                }
24555                mHandler.post(new Runnable() {
24556                    public void run() {
24557                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24558                                userHandle, 0);
24559                    } //end run
24560                });
24561            }
24562        }
24563    }
24564
24565    /** Called by UserManagerService */
24566    void createNewUser(int userId, String[] disallowedPackages) {
24567        synchronized (mInstallLock) {
24568            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24569        }
24570        synchronized (mPackages) {
24571            scheduleWritePackageRestrictionsLocked(userId);
24572            scheduleWritePackageListLocked(userId);
24573            applyFactoryDefaultBrowserLPw(userId);
24574            primeDomainVerificationsLPw(userId);
24575        }
24576    }
24577
24578    void onNewUserCreated(final int userId) {
24579        synchronized(mPackages) {
24580            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
24581        }
24582        // If permission review for legacy apps is required, we represent
24583        // dagerous permissions for such apps as always granted runtime
24584        // permissions to keep per user flag state whether review is needed.
24585        // Hence, if a new user is added we have to propagate dangerous
24586        // permission grants for these legacy apps.
24587        if (mPermissionReviewRequired) {
24588            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24589                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24590        }
24591    }
24592
24593    @Override
24594    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24595        mContext.enforceCallingOrSelfPermission(
24596                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24597                "Only package verification agents can read the verifier device identity");
24598
24599        synchronized (mPackages) {
24600            return mSettings.getVerifierDeviceIdentityLPw();
24601        }
24602    }
24603
24604    @Override
24605    public void setPermissionEnforced(String permission, boolean enforced) {
24606        // TODO: Now that we no longer change GID for storage, this should to away.
24607        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24608                "setPermissionEnforced");
24609        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24610            synchronized (mPackages) {
24611                if (mSettings.mReadExternalStorageEnforced == null
24612                        || mSettings.mReadExternalStorageEnforced != enforced) {
24613                    mSettings.mReadExternalStorageEnforced =
24614                            enforced ? Boolean.TRUE : Boolean.FALSE;
24615                    mSettings.writeLPr();
24616                }
24617            }
24618            // kill any non-foreground processes so we restart them and
24619            // grant/revoke the GID.
24620            final IActivityManager am = ActivityManager.getService();
24621            if (am != null) {
24622                final long token = Binder.clearCallingIdentity();
24623                try {
24624                    am.killProcessesBelowForeground("setPermissionEnforcement");
24625                } catch (RemoteException e) {
24626                } finally {
24627                    Binder.restoreCallingIdentity(token);
24628                }
24629            }
24630        } else {
24631            throw new IllegalArgumentException("No selective enforcement for " + permission);
24632        }
24633    }
24634
24635    @Override
24636    @Deprecated
24637    public boolean isPermissionEnforced(String permission) {
24638        // allow instant applications
24639        return true;
24640    }
24641
24642    @Override
24643    public boolean isStorageLow() {
24644        // allow instant applications
24645        final long token = Binder.clearCallingIdentity();
24646        try {
24647            final DeviceStorageMonitorInternal
24648                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24649            if (dsm != null) {
24650                return dsm.isMemoryLow();
24651            } else {
24652                return false;
24653            }
24654        } finally {
24655            Binder.restoreCallingIdentity(token);
24656        }
24657    }
24658
24659    @Override
24660    public IPackageInstaller getPackageInstaller() {
24661        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24662            return null;
24663        }
24664        return mInstallerService;
24665    }
24666
24667    private boolean userNeedsBadging(int userId) {
24668        int index = mUserNeedsBadging.indexOfKey(userId);
24669        if (index < 0) {
24670            final UserInfo userInfo;
24671            final long token = Binder.clearCallingIdentity();
24672            try {
24673                userInfo = sUserManager.getUserInfo(userId);
24674            } finally {
24675                Binder.restoreCallingIdentity(token);
24676            }
24677            final boolean b;
24678            if (userInfo != null && userInfo.isManagedProfile()) {
24679                b = true;
24680            } else {
24681                b = false;
24682            }
24683            mUserNeedsBadging.put(userId, b);
24684            return b;
24685        }
24686        return mUserNeedsBadging.valueAt(index);
24687    }
24688
24689    @Override
24690    public KeySet getKeySetByAlias(String packageName, String alias) {
24691        if (packageName == null || alias == null) {
24692            return null;
24693        }
24694        synchronized(mPackages) {
24695            final PackageParser.Package pkg = mPackages.get(packageName);
24696            if (pkg == null) {
24697                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24698                throw new IllegalArgumentException("Unknown package: " + packageName);
24699            }
24700            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24701            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24702                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24703                throw new IllegalArgumentException("Unknown package: " + packageName);
24704            }
24705            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24706            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24707        }
24708    }
24709
24710    @Override
24711    public KeySet getSigningKeySet(String packageName) {
24712        if (packageName == null) {
24713            return null;
24714        }
24715        synchronized(mPackages) {
24716            final int callingUid = Binder.getCallingUid();
24717            final int callingUserId = UserHandle.getUserId(callingUid);
24718            final PackageParser.Package pkg = mPackages.get(packageName);
24719            if (pkg == null) {
24720                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24721                throw new IllegalArgumentException("Unknown package: " + packageName);
24722            }
24723            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24724            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24725                // filter and pretend the package doesn't exist
24726                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24727                        + ", uid:" + callingUid);
24728                throw new IllegalArgumentException("Unknown package: " + packageName);
24729            }
24730            if (pkg.applicationInfo.uid != callingUid
24731                    && Process.SYSTEM_UID != callingUid) {
24732                throw new SecurityException("May not access signing KeySet of other apps.");
24733            }
24734            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24735            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24736        }
24737    }
24738
24739    @Override
24740    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24741        final int callingUid = Binder.getCallingUid();
24742        if (getInstantAppPackageName(callingUid) != null) {
24743            return false;
24744        }
24745        if (packageName == null || ks == null) {
24746            return false;
24747        }
24748        synchronized(mPackages) {
24749            final PackageParser.Package pkg = mPackages.get(packageName);
24750            if (pkg == null
24751                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24752                            UserHandle.getUserId(callingUid))) {
24753                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24754                throw new IllegalArgumentException("Unknown package: " + packageName);
24755            }
24756            IBinder ksh = ks.getToken();
24757            if (ksh instanceof KeySetHandle) {
24758                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24759                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24760            }
24761            return false;
24762        }
24763    }
24764
24765    @Override
24766    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24767        final int callingUid = Binder.getCallingUid();
24768        if (getInstantAppPackageName(callingUid) != null) {
24769            return false;
24770        }
24771        if (packageName == null || ks == null) {
24772            return false;
24773        }
24774        synchronized(mPackages) {
24775            final PackageParser.Package pkg = mPackages.get(packageName);
24776            if (pkg == null
24777                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24778                            UserHandle.getUserId(callingUid))) {
24779                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24780                throw new IllegalArgumentException("Unknown package: " + packageName);
24781            }
24782            IBinder ksh = ks.getToken();
24783            if (ksh instanceof KeySetHandle) {
24784                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24785                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24786            }
24787            return false;
24788        }
24789    }
24790
24791    private void deletePackageIfUnusedLPr(final String packageName) {
24792        PackageSetting ps = mSettings.mPackages.get(packageName);
24793        if (ps == null) {
24794            return;
24795        }
24796        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24797            // TODO Implement atomic delete if package is unused
24798            // It is currently possible that the package will be deleted even if it is installed
24799            // after this method returns.
24800            mHandler.post(new Runnable() {
24801                public void run() {
24802                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24803                            0, PackageManager.DELETE_ALL_USERS);
24804                }
24805            });
24806        }
24807    }
24808
24809    /**
24810     * Check and throw if the given before/after packages would be considered a
24811     * downgrade.
24812     */
24813    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24814            throws PackageManagerException {
24815        if (after.versionCode < before.mVersionCode) {
24816            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24817                    "Update version code " + after.versionCode + " is older than current "
24818                    + before.mVersionCode);
24819        } else if (after.versionCode == before.mVersionCode) {
24820            if (after.baseRevisionCode < before.baseRevisionCode) {
24821                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24822                        "Update base revision code " + after.baseRevisionCode
24823                        + " is older than current " + before.baseRevisionCode);
24824            }
24825
24826            if (!ArrayUtils.isEmpty(after.splitNames)) {
24827                for (int i = 0; i < after.splitNames.length; i++) {
24828                    final String splitName = after.splitNames[i];
24829                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24830                    if (j != -1) {
24831                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24832                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24833                                    "Update split " + splitName + " revision code "
24834                                    + after.splitRevisionCodes[i] + " is older than current "
24835                                    + before.splitRevisionCodes[j]);
24836                        }
24837                    }
24838                }
24839            }
24840        }
24841    }
24842
24843    private static class MoveCallbacks extends Handler {
24844        private static final int MSG_CREATED = 1;
24845        private static final int MSG_STATUS_CHANGED = 2;
24846
24847        private final RemoteCallbackList<IPackageMoveObserver>
24848                mCallbacks = new RemoteCallbackList<>();
24849
24850        private final SparseIntArray mLastStatus = new SparseIntArray();
24851
24852        public MoveCallbacks(Looper looper) {
24853            super(looper);
24854        }
24855
24856        public void register(IPackageMoveObserver callback) {
24857            mCallbacks.register(callback);
24858        }
24859
24860        public void unregister(IPackageMoveObserver callback) {
24861            mCallbacks.unregister(callback);
24862        }
24863
24864        @Override
24865        public void handleMessage(Message msg) {
24866            final SomeArgs args = (SomeArgs) msg.obj;
24867            final int n = mCallbacks.beginBroadcast();
24868            for (int i = 0; i < n; i++) {
24869                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24870                try {
24871                    invokeCallback(callback, msg.what, args);
24872                } catch (RemoteException ignored) {
24873                }
24874            }
24875            mCallbacks.finishBroadcast();
24876            args.recycle();
24877        }
24878
24879        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24880                throws RemoteException {
24881            switch (what) {
24882                case MSG_CREATED: {
24883                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24884                    break;
24885                }
24886                case MSG_STATUS_CHANGED: {
24887                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24888                    break;
24889                }
24890            }
24891        }
24892
24893        private void notifyCreated(int moveId, Bundle extras) {
24894            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24895
24896            final SomeArgs args = SomeArgs.obtain();
24897            args.argi1 = moveId;
24898            args.arg2 = extras;
24899            obtainMessage(MSG_CREATED, args).sendToTarget();
24900        }
24901
24902        private void notifyStatusChanged(int moveId, int status) {
24903            notifyStatusChanged(moveId, status, -1);
24904        }
24905
24906        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24907            Slog.v(TAG, "Move " + moveId + " status " + status);
24908
24909            final SomeArgs args = SomeArgs.obtain();
24910            args.argi1 = moveId;
24911            args.argi2 = status;
24912            args.arg3 = estMillis;
24913            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24914
24915            synchronized (mLastStatus) {
24916                mLastStatus.put(moveId, status);
24917            }
24918        }
24919    }
24920
24921    private final static class OnPermissionChangeListeners extends Handler {
24922        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24923
24924        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24925                new RemoteCallbackList<>();
24926
24927        public OnPermissionChangeListeners(Looper looper) {
24928            super(looper);
24929        }
24930
24931        @Override
24932        public void handleMessage(Message msg) {
24933            switch (msg.what) {
24934                case MSG_ON_PERMISSIONS_CHANGED: {
24935                    final int uid = msg.arg1;
24936                    handleOnPermissionsChanged(uid);
24937                } break;
24938            }
24939        }
24940
24941        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24942            mPermissionListeners.register(listener);
24943
24944        }
24945
24946        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24947            mPermissionListeners.unregister(listener);
24948        }
24949
24950        public void onPermissionsChanged(int uid) {
24951            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24952                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24953            }
24954        }
24955
24956        private void handleOnPermissionsChanged(int uid) {
24957            final int count = mPermissionListeners.beginBroadcast();
24958            try {
24959                for (int i = 0; i < count; i++) {
24960                    IOnPermissionsChangeListener callback = mPermissionListeners
24961                            .getBroadcastItem(i);
24962                    try {
24963                        callback.onPermissionsChanged(uid);
24964                    } catch (RemoteException e) {
24965                        Log.e(TAG, "Permission listener is dead", e);
24966                    }
24967                }
24968            } finally {
24969                mPermissionListeners.finishBroadcast();
24970            }
24971        }
24972    }
24973
24974    private class PackageManagerNative extends IPackageManagerNative.Stub {
24975        @Override
24976        public String[] getNamesForUids(int[] uids) throws RemoteException {
24977            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24978            // massage results so they can be parsed by the native binder
24979            for (int i = results.length - 1; i >= 0; --i) {
24980                if (results[i] == null) {
24981                    results[i] = "";
24982                }
24983            }
24984            return results;
24985        }
24986
24987        // NB: this differentiates between preloads and sideloads
24988        @Override
24989        public String getInstallerForPackage(String packageName) throws RemoteException {
24990            final String installerName = getInstallerPackageName(packageName);
24991            if (!TextUtils.isEmpty(installerName)) {
24992                return installerName;
24993            }
24994            // differentiate between preload and sideload
24995            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24996            ApplicationInfo appInfo = getApplicationInfo(packageName,
24997                                    /*flags*/ 0,
24998                                    /*userId*/ callingUser);
24999            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25000                return "preload";
25001            }
25002            return "";
25003        }
25004
25005        @Override
25006        public int getVersionCodeForPackage(String packageName) throws RemoteException {
25007            try {
25008                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25009                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25010                if (pInfo != null) {
25011                    return pInfo.versionCode;
25012                }
25013            } catch (Exception e) {
25014            }
25015            return 0;
25016        }
25017    }
25018
25019    private class PackageManagerInternalImpl extends PackageManagerInternal {
25020        @Override
25021        public Object getPermissionTEMP(String permName) {
25022            synchronized (mPackages) {
25023                return mSettings.mPermissions.get(permName);
25024            }
25025        }
25026
25027        @Override
25028        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
25029                int flagValues, int userId) {
25030            PackageManagerService.this.updatePermissionFlags(
25031                    permName, packageName, flagMask, flagValues, userId);
25032        }
25033
25034        @Override
25035        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
25036            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
25037        }
25038
25039        @Override
25040        public PackageParser.Package getPackage(String packageName) {
25041            synchronized (mPackages) {
25042                return mPackages.get(packageName);
25043            }
25044        }
25045
25046        @Override
25047        public PackageParser.Package getDisabledPackage(String packageName) {
25048            synchronized (mPackages) {
25049                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
25050                return (ps != null) ? ps.pkg : null;
25051            }
25052        }
25053
25054        @Override
25055        public String getKnownPackageName(int knownPackage, int userId) {
25056            switch(knownPackage) {
25057                case PackageManagerInternal.PACKAGE_BROWSER:
25058                    return getDefaultBrowserPackageName(userId);
25059                case PackageManagerInternal.PACKAGE_INSTALLER:
25060                    return mRequiredInstallerPackage;
25061                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
25062                    return mSetupWizardPackage;
25063                case PackageManagerInternal.PACKAGE_SYSTEM:
25064                    return "android";
25065                case PackageManagerInternal.PACKAGE_VERIFIER:
25066                    return mRequiredVerifierPackage;
25067            }
25068            return null;
25069        }
25070
25071        @Override
25072        public boolean isResolveActivityComponent(ComponentInfo component) {
25073            return mResolveActivity.packageName.equals(component.packageName)
25074                    && mResolveActivity.name.equals(component.name);
25075        }
25076
25077        @Override
25078        public void setLocationPackagesProvider(PackagesProvider provider) {
25079            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
25080        }
25081
25082        @Override
25083        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25084            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
25085        }
25086
25087        @Override
25088        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25089            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
25090        }
25091
25092        @Override
25093        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25094            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
25095        }
25096
25097        @Override
25098        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25099            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
25100        }
25101
25102        @Override
25103        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25104            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
25105        }
25106
25107        @Override
25108        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25109            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
25110        }
25111
25112        @Override
25113        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25114            synchronized (mPackages) {
25115                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25116            }
25117            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
25118        }
25119
25120        @Override
25121        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25122            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
25123                    packageName, userId);
25124        }
25125
25126        @Override
25127        public void setKeepUninstalledPackages(final List<String> packageList) {
25128            Preconditions.checkNotNull(packageList);
25129            List<String> removedFromList = null;
25130            synchronized (mPackages) {
25131                if (mKeepUninstalledPackages != null) {
25132                    final int packagesCount = mKeepUninstalledPackages.size();
25133                    for (int i = 0; i < packagesCount; i++) {
25134                        String oldPackage = mKeepUninstalledPackages.get(i);
25135                        if (packageList != null && packageList.contains(oldPackage)) {
25136                            continue;
25137                        }
25138                        if (removedFromList == null) {
25139                            removedFromList = new ArrayList<>();
25140                        }
25141                        removedFromList.add(oldPackage);
25142                    }
25143                }
25144                mKeepUninstalledPackages = new ArrayList<>(packageList);
25145                if (removedFromList != null) {
25146                    final int removedCount = removedFromList.size();
25147                    for (int i = 0; i < removedCount; i++) {
25148                        deletePackageIfUnusedLPr(removedFromList.get(i));
25149                    }
25150                }
25151            }
25152        }
25153
25154        @Override
25155        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25156            synchronized (mPackages) {
25157                // If we do not support permission review, done.
25158                if (!mPermissionReviewRequired) {
25159                    return false;
25160                }
25161
25162                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25163                if (packageSetting == null) {
25164                    return false;
25165                }
25166
25167                // Permission review applies only to apps not supporting the new permission model.
25168                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25169                    return false;
25170                }
25171
25172                // Legacy apps have the permission and get user consent on launch.
25173                PermissionsState permissionsState = packageSetting.getPermissionsState();
25174                return permissionsState.isPermissionReviewRequired(userId);
25175            }
25176        }
25177
25178        @Override
25179        public PackageInfo getPackageInfo(
25180                String packageName, int flags, int filterCallingUid, int userId) {
25181            return PackageManagerService.this
25182                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25183                            flags, filterCallingUid, userId);
25184        }
25185
25186        @Override
25187        public ApplicationInfo getApplicationInfo(
25188                String packageName, int flags, int filterCallingUid, int userId) {
25189            return PackageManagerService.this
25190                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25191        }
25192
25193        @Override
25194        public ActivityInfo getActivityInfo(
25195                ComponentName component, int flags, int filterCallingUid, int userId) {
25196            return PackageManagerService.this
25197                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25198        }
25199
25200        @Override
25201        public List<ResolveInfo> queryIntentActivities(
25202                Intent intent, int flags, int filterCallingUid, int userId) {
25203            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25204            return PackageManagerService.this
25205                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25206                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25207        }
25208
25209        @Override
25210        public List<ResolveInfo> queryIntentServices(
25211                Intent intent, int flags, int callingUid, int userId) {
25212            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25213            return PackageManagerService.this
25214                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
25215                            false);
25216        }
25217
25218        @Override
25219        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25220                int userId) {
25221            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25222        }
25223
25224        @Override
25225        public void setDeviceAndProfileOwnerPackages(
25226                int deviceOwnerUserId, String deviceOwnerPackage,
25227                SparseArray<String> profileOwnerPackages) {
25228            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25229                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25230        }
25231
25232        @Override
25233        public boolean isPackageDataProtected(int userId, String packageName) {
25234            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25235        }
25236
25237        @Override
25238        public boolean isPackageEphemeral(int userId, String packageName) {
25239            synchronized (mPackages) {
25240                final PackageSetting ps = mSettings.mPackages.get(packageName);
25241                return ps != null ? ps.getInstantApp(userId) : false;
25242            }
25243        }
25244
25245        @Override
25246        public boolean wasPackageEverLaunched(String packageName, int userId) {
25247            synchronized (mPackages) {
25248                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25249            }
25250        }
25251
25252        @Override
25253        public void grantRuntimePermission(String packageName, String name, int userId,
25254                boolean overridePolicy) {
25255            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25256                    overridePolicy);
25257        }
25258
25259        @Override
25260        public void revokeRuntimePermission(String packageName, String name, int userId,
25261                boolean overridePolicy) {
25262            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25263                    overridePolicy);
25264        }
25265
25266        @Override
25267        public String getNameForUid(int uid) {
25268            return PackageManagerService.this.getNameForUid(uid);
25269        }
25270
25271        @Override
25272        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25273                Intent origIntent, String resolvedType, String callingPackage,
25274                Bundle verificationBundle, int userId) {
25275            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25276                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25277                    userId);
25278        }
25279
25280        @Override
25281        public void grantEphemeralAccess(int userId, Intent intent,
25282                int targetAppId, int ephemeralAppId) {
25283            synchronized (mPackages) {
25284                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25285                        targetAppId, ephemeralAppId);
25286            }
25287        }
25288
25289        @Override
25290        public boolean isInstantAppInstallerComponent(ComponentName component) {
25291            synchronized (mPackages) {
25292                return mInstantAppInstallerActivity != null
25293                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25294            }
25295        }
25296
25297        @Override
25298        public void pruneInstantApps() {
25299            mInstantAppRegistry.pruneInstantApps();
25300        }
25301
25302        @Override
25303        public String getSetupWizardPackageName() {
25304            return mSetupWizardPackage;
25305        }
25306
25307        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25308            if (policy != null) {
25309                mExternalSourcesPolicy = policy;
25310            }
25311        }
25312
25313        @Override
25314        public boolean isPackagePersistent(String packageName) {
25315            synchronized (mPackages) {
25316                PackageParser.Package pkg = mPackages.get(packageName);
25317                return pkg != null
25318                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25319                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25320                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25321                        : false;
25322            }
25323        }
25324
25325        @Override
25326        public List<PackageInfo> getOverlayPackages(int userId) {
25327            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25328            synchronized (mPackages) {
25329                for (PackageParser.Package p : mPackages.values()) {
25330                    if (p.mOverlayTarget != null) {
25331                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25332                        if (pkg != null) {
25333                            overlayPackages.add(pkg);
25334                        }
25335                    }
25336                }
25337            }
25338            return overlayPackages;
25339        }
25340
25341        @Override
25342        public List<String> getTargetPackageNames(int userId) {
25343            List<String> targetPackages = new ArrayList<>();
25344            synchronized (mPackages) {
25345                for (PackageParser.Package p : mPackages.values()) {
25346                    if (p.mOverlayTarget == null) {
25347                        targetPackages.add(p.packageName);
25348                    }
25349                }
25350            }
25351            return targetPackages;
25352        }
25353
25354        @Override
25355        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25356                @Nullable List<String> overlayPackageNames) {
25357            synchronized (mPackages) {
25358                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25359                    Slog.e(TAG, "failed to find package " + targetPackageName);
25360                    return false;
25361                }
25362                ArrayList<String> overlayPaths = null;
25363                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25364                    final int N = overlayPackageNames.size();
25365                    overlayPaths = new ArrayList<>(N);
25366                    for (int i = 0; i < N; i++) {
25367                        final String packageName = overlayPackageNames.get(i);
25368                        final PackageParser.Package pkg = mPackages.get(packageName);
25369                        if (pkg == null) {
25370                            Slog.e(TAG, "failed to find package " + packageName);
25371                            return false;
25372                        }
25373                        overlayPaths.add(pkg.baseCodePath);
25374                    }
25375                }
25376
25377                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25378                ps.setOverlayPaths(overlayPaths, userId);
25379                return true;
25380            }
25381        }
25382
25383        @Override
25384        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25385                int flags, int userId, boolean resolveForStart) {
25386            return resolveIntentInternal(
25387                    intent, resolvedType, flags, userId, resolveForStart);
25388        }
25389
25390        @Override
25391        public ResolveInfo resolveService(Intent intent, String resolvedType,
25392                int flags, int userId, int callingUid) {
25393            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25394        }
25395
25396        @Override
25397        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
25398            return PackageManagerService.this.resolveContentProviderInternal(
25399                    name, flags, userId);
25400        }
25401
25402        @Override
25403        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25404            synchronized (mPackages) {
25405                mIsolatedOwners.put(isolatedUid, ownerUid);
25406            }
25407        }
25408
25409        @Override
25410        public void removeIsolatedUid(int isolatedUid) {
25411            synchronized (mPackages) {
25412                mIsolatedOwners.delete(isolatedUid);
25413            }
25414        }
25415
25416        @Override
25417        public int getUidTargetSdkVersion(int uid) {
25418            synchronized (mPackages) {
25419                return getUidTargetSdkVersionLockedLPr(uid);
25420            }
25421        }
25422
25423        @Override
25424        public boolean canAccessInstantApps(int callingUid, int userId) {
25425            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25426        }
25427
25428        @Override
25429        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25430            synchronized (mPackages) {
25431                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25432            }
25433        }
25434
25435        @Override
25436        public void notifyPackageUse(String packageName, int reason) {
25437            synchronized (mPackages) {
25438                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25439            }
25440        }
25441    }
25442
25443    @Override
25444    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25445        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25446        synchronized (mPackages) {
25447            final long identity = Binder.clearCallingIdentity();
25448            try {
25449                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
25450                        packageNames, userId);
25451            } finally {
25452                Binder.restoreCallingIdentity(identity);
25453            }
25454        }
25455    }
25456
25457    @Override
25458    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25459        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25460        synchronized (mPackages) {
25461            final long identity = Binder.clearCallingIdentity();
25462            try {
25463                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
25464                        packageNames, userId);
25465            } finally {
25466                Binder.restoreCallingIdentity(identity);
25467            }
25468        }
25469    }
25470
25471    private static void enforceSystemOrPhoneCaller(String tag) {
25472        int callingUid = Binder.getCallingUid();
25473        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25474            throw new SecurityException(
25475                    "Cannot call " + tag + " from UID " + callingUid);
25476        }
25477    }
25478
25479    boolean isHistoricalPackageUsageAvailable() {
25480        return mPackageUsage.isHistoricalPackageUsageAvailable();
25481    }
25482
25483    /**
25484     * Return a <b>copy</b> of the collection of packages known to the package manager.
25485     * @return A copy of the values of mPackages.
25486     */
25487    Collection<PackageParser.Package> getPackages() {
25488        synchronized (mPackages) {
25489            return new ArrayList<>(mPackages.values());
25490        }
25491    }
25492
25493    /**
25494     * Logs process start information (including base APK hash) to the security log.
25495     * @hide
25496     */
25497    @Override
25498    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25499            String apkFile, int pid) {
25500        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25501            return;
25502        }
25503        if (!SecurityLog.isLoggingEnabled()) {
25504            return;
25505        }
25506        Bundle data = new Bundle();
25507        data.putLong("startTimestamp", System.currentTimeMillis());
25508        data.putString("processName", processName);
25509        data.putInt("uid", uid);
25510        data.putString("seinfo", seinfo);
25511        data.putString("apkFile", apkFile);
25512        data.putInt("pid", pid);
25513        Message msg = mProcessLoggingHandler.obtainMessage(
25514                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25515        msg.setData(data);
25516        mProcessLoggingHandler.sendMessage(msg);
25517    }
25518
25519    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25520        return mCompilerStats.getPackageStats(pkgName);
25521    }
25522
25523    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25524        return getOrCreateCompilerPackageStats(pkg.packageName);
25525    }
25526
25527    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25528        return mCompilerStats.getOrCreatePackageStats(pkgName);
25529    }
25530
25531    public void deleteCompilerPackageStats(String pkgName) {
25532        mCompilerStats.deletePackageStats(pkgName);
25533    }
25534
25535    @Override
25536    public int getInstallReason(String packageName, int userId) {
25537        final int callingUid = Binder.getCallingUid();
25538        enforceCrossUserPermission(callingUid, userId,
25539                true /* requireFullPermission */, false /* checkShell */,
25540                "get install reason");
25541        synchronized (mPackages) {
25542            final PackageSetting ps = mSettings.mPackages.get(packageName);
25543            if (filterAppAccessLPr(ps, callingUid, userId)) {
25544                return PackageManager.INSTALL_REASON_UNKNOWN;
25545            }
25546            if (ps != null) {
25547                return ps.getInstallReason(userId);
25548            }
25549        }
25550        return PackageManager.INSTALL_REASON_UNKNOWN;
25551    }
25552
25553    @Override
25554    public boolean canRequestPackageInstalls(String packageName, int userId) {
25555        return canRequestPackageInstallsInternal(packageName, 0, userId,
25556                true /* throwIfPermNotDeclared*/);
25557    }
25558
25559    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25560            boolean throwIfPermNotDeclared) {
25561        int callingUid = Binder.getCallingUid();
25562        int uid = getPackageUid(packageName, 0, userId);
25563        if (callingUid != uid && callingUid != Process.ROOT_UID
25564                && callingUid != Process.SYSTEM_UID) {
25565            throw new SecurityException(
25566                    "Caller uid " + callingUid + " does not own package " + packageName);
25567        }
25568        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25569        if (info == null) {
25570            return false;
25571        }
25572        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25573            return false;
25574        }
25575        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25576        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25577        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25578            if (throwIfPermNotDeclared) {
25579                throw new SecurityException("Need to declare " + appOpPermission
25580                        + " to call this api");
25581            } else {
25582                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25583                return false;
25584            }
25585        }
25586        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25587            return false;
25588        }
25589        if (mExternalSourcesPolicy != null) {
25590            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25591            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25592                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25593            }
25594        }
25595        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25596    }
25597
25598    @Override
25599    public ComponentName getInstantAppResolverSettingsComponent() {
25600        return mInstantAppResolverSettingsComponent;
25601    }
25602
25603    @Override
25604    public ComponentName getInstantAppInstallerComponent() {
25605        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25606            return null;
25607        }
25608        return mInstantAppInstallerActivity == null
25609                ? null : mInstantAppInstallerActivity.getComponentName();
25610    }
25611
25612    @Override
25613    public String getInstantAppAndroidId(String packageName, int userId) {
25614        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25615                "getInstantAppAndroidId");
25616        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25617                true /* requireFullPermission */, false /* checkShell */,
25618                "getInstantAppAndroidId");
25619        // Make sure the target is an Instant App.
25620        if (!isInstantApp(packageName, userId)) {
25621            return null;
25622        }
25623        synchronized (mPackages) {
25624            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25625        }
25626    }
25627
25628    boolean canHaveOatDir(String packageName) {
25629        synchronized (mPackages) {
25630            PackageParser.Package p = mPackages.get(packageName);
25631            if (p == null) {
25632                return false;
25633            }
25634            return p.canHaveOatDir();
25635        }
25636    }
25637
25638    private String getOatDir(PackageParser.Package pkg) {
25639        if (!pkg.canHaveOatDir()) {
25640            return null;
25641        }
25642        File codePath = new File(pkg.codePath);
25643        if (codePath.isDirectory()) {
25644            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25645        }
25646        return null;
25647    }
25648
25649    void deleteOatArtifactsOfPackage(String packageName) {
25650        final String[] instructionSets;
25651        final List<String> codePaths;
25652        final String oatDir;
25653        final PackageParser.Package pkg;
25654        synchronized (mPackages) {
25655            pkg = mPackages.get(packageName);
25656        }
25657        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25658        codePaths = pkg.getAllCodePaths();
25659        oatDir = getOatDir(pkg);
25660
25661        for (String codePath : codePaths) {
25662            for (String isa : instructionSets) {
25663                try {
25664                    mInstaller.deleteOdex(codePath, isa, oatDir);
25665                } catch (InstallerException e) {
25666                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25667                }
25668            }
25669        }
25670    }
25671
25672    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25673        Set<String> unusedPackages = new HashSet<>();
25674        long currentTimeInMillis = System.currentTimeMillis();
25675        synchronized (mPackages) {
25676            for (PackageParser.Package pkg : mPackages.values()) {
25677                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25678                if (ps == null) {
25679                    continue;
25680                }
25681                PackageDexUsage.PackageUseInfo packageUseInfo =
25682                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25683                if (PackageManagerServiceUtils
25684                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25685                                downgradeTimeThresholdMillis, packageUseInfo,
25686                                pkg.getLatestPackageUseTimeInMills(),
25687                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25688                    unusedPackages.add(pkg.packageName);
25689                }
25690            }
25691        }
25692        return unusedPackages;
25693    }
25694}
25695
25696interface PackageSender {
25697    void sendPackageBroadcast(final String action, final String pkg,
25698        final Bundle extras, final int flags, final String targetPkg,
25699        final IIntentReceiver finishedReceiver, final int[] userIds);
25700    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25701        boolean includeStopped, int appId, int... userIds);
25702}
25703