PackageManagerService.java revision efc022768eba2f33d3fadbda7eaa6adf1730d3fc
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.PermissionsState.PERMISSION_OPERATION_FAILURE;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
108import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
109
110import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
111
112import android.Manifest;
113import android.annotation.IntDef;
114import android.annotation.NonNull;
115import android.annotation.Nullable;
116import android.app.ActivityManager;
117import android.app.AppOpsManager;
118import android.app.IActivityManager;
119import android.app.ResourcesManager;
120import android.app.admin.IDevicePolicyManager;
121import android.app.admin.SecurityLog;
122import android.app.backup.IBackupManager;
123import android.content.BroadcastReceiver;
124import android.content.ComponentName;
125import android.content.ContentResolver;
126import android.content.Context;
127import android.content.IIntentReceiver;
128import android.content.Intent;
129import android.content.IntentFilter;
130import android.content.IntentSender;
131import android.content.IntentSender.SendIntentException;
132import android.content.ServiceConnection;
133import android.content.pm.ActivityInfo;
134import android.content.pm.ApplicationInfo;
135import android.content.pm.AppsQueryHelper;
136import android.content.pm.AuxiliaryResolveInfo;
137import android.content.pm.ChangedPackages;
138import android.content.pm.ComponentInfo;
139import android.content.pm.FallbackCategoryProvider;
140import android.content.pm.FeatureInfo;
141import android.content.pm.IDexModuleRegisterCallback;
142import android.content.pm.IOnPermissionsChangeListener;
143import android.content.pm.IPackageDataObserver;
144import android.content.pm.IPackageDeleteObserver;
145import android.content.pm.IPackageDeleteObserver2;
146import android.content.pm.IPackageInstallObserver2;
147import android.content.pm.IPackageInstaller;
148import android.content.pm.IPackageManager;
149import android.content.pm.IPackageManagerNative;
150import android.content.pm.IPackageMoveObserver;
151import android.content.pm.IPackageStatsObserver;
152import android.content.pm.InstantAppInfo;
153import android.content.pm.InstantAppRequest;
154import android.content.pm.InstantAppResolveInfo;
155import android.content.pm.InstrumentationInfo;
156import android.content.pm.IntentFilterVerificationInfo;
157import android.content.pm.KeySet;
158import android.content.pm.PackageCleanItem;
159import android.content.pm.PackageInfo;
160import android.content.pm.PackageInfoLite;
161import android.content.pm.PackageInstaller;
162import android.content.pm.PackageManager;
163import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
164import android.content.pm.PackageManagerInternal;
165import android.content.pm.PackageParser;
166import android.content.pm.PackageParser.ActivityIntentInfo;
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.PermissionsState.PermissionState;
287import com.android.server.pm.Settings.DatabaseVersion;
288import com.android.server.pm.Settings.VersionInfo;
289import com.android.server.pm.dex.DexManager;
290import com.android.server.pm.dex.DexoptOptions;
291import com.android.server.pm.dex.PackageDexUsage;
292import com.android.server.storage.DeviceStorageMonitorInternal;
293
294import dalvik.system.CloseGuard;
295import dalvik.system.DexFile;
296import dalvik.system.VMRuntime;
297
298import libcore.io.IoUtils;
299import libcore.io.Streams;
300import libcore.util.EmptyArray;
301
302import org.xmlpull.v1.XmlPullParser;
303import org.xmlpull.v1.XmlPullParserException;
304import org.xmlpull.v1.XmlSerializer;
305
306import java.io.BufferedOutputStream;
307import java.io.BufferedReader;
308import java.io.ByteArrayInputStream;
309import java.io.ByteArrayOutputStream;
310import java.io.File;
311import java.io.FileDescriptor;
312import java.io.FileInputStream;
313import java.io.FileOutputStream;
314import java.io.FileReader;
315import java.io.FilenameFilter;
316import java.io.IOException;
317import java.io.InputStream;
318import java.io.OutputStream;
319import java.io.PrintWriter;
320import java.lang.annotation.Retention;
321import java.lang.annotation.RetentionPolicy;
322import java.nio.charset.StandardCharsets;
323import java.security.DigestInputStream;
324import java.security.MessageDigest;
325import java.security.NoSuchAlgorithmException;
326import java.security.PublicKey;
327import java.security.SecureRandom;
328import java.security.cert.Certificate;
329import java.security.cert.CertificateEncodingException;
330import java.security.cert.CertificateException;
331import java.text.SimpleDateFormat;
332import java.util.ArrayList;
333import java.util.Arrays;
334import java.util.Collection;
335import java.util.Collections;
336import java.util.Comparator;
337import java.util.Date;
338import java.util.HashMap;
339import java.util.HashSet;
340import java.util.Iterator;
341import java.util.List;
342import java.util.Map;
343import java.util.Objects;
344import java.util.Set;
345import java.util.concurrent.CountDownLatch;
346import java.util.concurrent.Future;
347import java.util.concurrent.TimeUnit;
348import java.util.concurrent.atomic.AtomicBoolean;
349import java.util.concurrent.atomic.AtomicInteger;
350import java.util.zip.GZIPInputStream;
351
352/**
353 * Keep track of all those APKs everywhere.
354 * <p>
355 * Internally there are two important locks:
356 * <ul>
357 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
358 * and other related state. It is a fine-grained lock that should only be held
359 * momentarily, as it's one of the most contended locks in the system.
360 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
361 * operations typically involve heavy lifting of application data on disk. Since
362 * {@code installd} is single-threaded, and it's operations can often be slow,
363 * this lock should never be acquired while already holding {@link #mPackages}.
364 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
365 * holding {@link #mInstallLock}.
366 * </ul>
367 * Many internal methods rely on the caller to hold the appropriate locks, and
368 * this contract is expressed through method name suffixes:
369 * <ul>
370 * <li>fooLI(): the caller must hold {@link #mInstallLock}
371 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
372 * being modified must be frozen
373 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
374 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
375 * </ul>
376 * <p>
377 * Because this class is very central to the platform's security; please run all
378 * CTS and unit tests whenever making modifications:
379 *
380 * <pre>
381 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
382 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
383 * </pre>
384 */
385public class PackageManagerService extends IPackageManager.Stub
386        implements PackageSender {
387    static final String TAG = "PackageManager";
388    static final boolean DEBUG_SETTINGS = false;
389    static final boolean DEBUG_PREFERRED = false;
390    static final boolean DEBUG_UPGRADE = false;
391    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
392    private static final boolean DEBUG_BACKUP = false;
393    private static final boolean DEBUG_INSTALL = false;
394    private static final boolean DEBUG_REMOVE = false;
395    private static final boolean DEBUG_BROADCASTS = false;
396    private static final boolean DEBUG_SHOW_INFO = false;
397    private static final boolean DEBUG_PACKAGE_INFO = false;
398    private static final boolean DEBUG_INTENT_MATCHING = false;
399    private static final boolean DEBUG_PACKAGE_SCANNING = false;
400    private static final boolean DEBUG_VERIFY = false;
401    private static final boolean DEBUG_FILTERS = false;
402    private static final boolean DEBUG_PERMISSIONS = false;
403    private static final boolean DEBUG_SHARED_LIBRARIES = false;
404    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
405
406    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
407    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
408    // user, but by default initialize to this.
409    public static final boolean DEBUG_DEXOPT = false;
410
411    private static final boolean DEBUG_ABI_SELECTION = false;
412    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
413    private static final boolean DEBUG_TRIAGED_MISSING = false;
414    private static final boolean DEBUG_APP_DATA = false;
415
416    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
417    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
418
419    private static final boolean HIDE_EPHEMERAL_APIS = false;
420
421    private static final boolean ENABLE_FREE_CACHE_V2 =
422            SystemProperties.getBoolean("fw.free_cache_v2", true);
423
424    private static final int RADIO_UID = Process.PHONE_UID;
425    private static final int LOG_UID = Process.LOG_UID;
426    private static final int NFC_UID = Process.NFC_UID;
427    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
428    private static final int SHELL_UID = Process.SHELL_UID;
429
430    // Cap the size of permission trees that 3rd party apps can define
431    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
432
433    // Suffix used during package installation when copying/moving
434    // package apks to install directory.
435    private static final String INSTALL_PACKAGE_SUFFIX = "-";
436
437    static final int SCAN_NO_DEX = 1<<1;
438    static final int SCAN_FORCE_DEX = 1<<2;
439    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
440    static final int SCAN_NEW_INSTALL = 1<<4;
441    static final int SCAN_UPDATE_TIME = 1<<5;
442    static final int SCAN_BOOTING = 1<<6;
443    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
444    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
445    static final int SCAN_REPLACING = 1<<9;
446    static final int SCAN_REQUIRE_KNOWN = 1<<10;
447    static final int SCAN_MOVE = 1<<11;
448    static final int SCAN_INITIAL = 1<<12;
449    static final int SCAN_CHECK_ONLY = 1<<13;
450    static final int SCAN_DONT_KILL_APP = 1<<14;
451    static final int SCAN_IGNORE_FROZEN = 1<<15;
452    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
453    static final int SCAN_AS_INSTANT_APP = 1<<17;
454    static final int SCAN_AS_FULL_APP = 1<<18;
455    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
456    /** Should not be with the scan flags */
457    static final int FLAGS_REMOVE_CHATTY = 1<<31;
458
459    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
460    /** Extension of the compressed packages */
461    private final static String COMPRESSED_EXTENSION = ".gz";
462    /** Suffix of stub packages on the system partition */
463    private final static String STUB_SUFFIX = "-Stub";
464
465    private static final int[] EMPTY_INT_ARRAY = new int[0];
466
467    private static final int TYPE_UNKNOWN = 0;
468    private static final int TYPE_ACTIVITY = 1;
469    private static final int TYPE_RECEIVER = 2;
470    private static final int TYPE_SERVICE = 3;
471    private static final int TYPE_PROVIDER = 4;
472    @IntDef(prefix = { "TYPE_" }, value = {
473            TYPE_UNKNOWN,
474            TYPE_ACTIVITY,
475            TYPE_RECEIVER,
476            TYPE_SERVICE,
477            TYPE_PROVIDER,
478    })
479    @Retention(RetentionPolicy.SOURCE)
480    public @interface ComponentType {}
481
482    /**
483     * Timeout (in milliseconds) after which the watchdog should declare that
484     * our handler thread is wedged.  The usual default for such things is one
485     * minute but we sometimes do very lengthy I/O operations on this thread,
486     * such as installing multi-gigabyte applications, so ours needs to be longer.
487     */
488    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
489
490    /**
491     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
492     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
493     * settings entry if available, otherwise we use the hardcoded default.  If it's been
494     * more than this long since the last fstrim, we force one during the boot sequence.
495     *
496     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
497     * one gets run at the next available charging+idle time.  This final mandatory
498     * no-fstrim check kicks in only of the other scheduling criteria is never met.
499     */
500    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
501
502    /**
503     * Whether verification is enabled by default.
504     */
505    private static final boolean DEFAULT_VERIFY_ENABLE = true;
506
507    /**
508     * The default maximum time to wait for the verification agent to return in
509     * milliseconds.
510     */
511    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
512
513    /**
514     * The default response for package verification timeout.
515     *
516     * This can be either PackageManager.VERIFICATION_ALLOW or
517     * PackageManager.VERIFICATION_REJECT.
518     */
519    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
520
521    static final String PLATFORM_PACKAGE_NAME = "android";
522
523    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
524
525    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
526            DEFAULT_CONTAINER_PACKAGE,
527            "com.android.defcontainer.DefaultContainerService");
528
529    private static final String KILL_APP_REASON_GIDS_CHANGED =
530            "permission grant or revoke changed gids";
531
532    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
533            "permissions revoked";
534
535    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
536
537    private static final String PACKAGE_SCHEME = "package";
538
539    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
540
541    /** Permission grant: not grant the permission. */
542    private static final int GRANT_DENIED = 1;
543
544    /** Permission grant: grant the permission as an install permission. */
545    private static final int GRANT_INSTALL = 2;
546
547    /** Permission grant: grant the permission as a runtime one. */
548    private static final int GRANT_RUNTIME = 3;
549
550    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
551    private static final int GRANT_UPGRADE = 4;
552
553    /** Canonical intent used to identify what counts as a "web browser" app */
554    private static final Intent sBrowserIntent;
555    static {
556        sBrowserIntent = new Intent();
557        sBrowserIntent.setAction(Intent.ACTION_VIEW);
558        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
559        sBrowserIntent.setData(Uri.parse("http:"));
560    }
561
562    /**
563     * The set of all protected actions [i.e. those actions for which a high priority
564     * intent filter is disallowed].
565     */
566    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
567    static {
568        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
569        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
570        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
571        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
572    }
573
574    // Compilation reasons.
575    public static final int REASON_FIRST_BOOT = 0;
576    public static final int REASON_BOOT = 1;
577    public static final int REASON_INSTALL = 2;
578    public static final int REASON_BACKGROUND_DEXOPT = 3;
579    public static final int REASON_AB_OTA = 4;
580    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
581    public static final int REASON_SHARED = 6;
582
583    public static final int REASON_LAST = REASON_SHARED;
584
585    /** All dangerous permission names in the same order as the events in MetricsEvent */
586    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
587            Manifest.permission.READ_CALENDAR,
588            Manifest.permission.WRITE_CALENDAR,
589            Manifest.permission.CAMERA,
590            Manifest.permission.READ_CONTACTS,
591            Manifest.permission.WRITE_CONTACTS,
592            Manifest.permission.GET_ACCOUNTS,
593            Manifest.permission.ACCESS_FINE_LOCATION,
594            Manifest.permission.ACCESS_COARSE_LOCATION,
595            Manifest.permission.RECORD_AUDIO,
596            Manifest.permission.READ_PHONE_STATE,
597            Manifest.permission.CALL_PHONE,
598            Manifest.permission.READ_CALL_LOG,
599            Manifest.permission.WRITE_CALL_LOG,
600            Manifest.permission.ADD_VOICEMAIL,
601            Manifest.permission.USE_SIP,
602            Manifest.permission.PROCESS_OUTGOING_CALLS,
603            Manifest.permission.READ_CELL_BROADCASTS,
604            Manifest.permission.BODY_SENSORS,
605            Manifest.permission.SEND_SMS,
606            Manifest.permission.RECEIVE_SMS,
607            Manifest.permission.READ_SMS,
608            Manifest.permission.RECEIVE_WAP_PUSH,
609            Manifest.permission.RECEIVE_MMS,
610            Manifest.permission.READ_EXTERNAL_STORAGE,
611            Manifest.permission.WRITE_EXTERNAL_STORAGE,
612            Manifest.permission.READ_PHONE_NUMBERS,
613            Manifest.permission.ANSWER_PHONE_CALLS);
614
615
616    /**
617     * Version number for the package parser cache. Increment this whenever the format or
618     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
619     */
620    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
621
622    /**
623     * Whether the package parser cache is enabled.
624     */
625    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
626
627    final ServiceThread mHandlerThread;
628
629    final PackageHandler mHandler;
630
631    private final ProcessLoggingHandler mProcessLoggingHandler;
632
633    /**
634     * Messages for {@link #mHandler} that need to wait for system ready before
635     * being dispatched.
636     */
637    private ArrayList<Message> mPostSystemReadyMessages;
638
639    final int mSdkVersion = Build.VERSION.SDK_INT;
640
641    final Context mContext;
642    final boolean mFactoryTest;
643    final boolean mOnlyCore;
644    final DisplayMetrics mMetrics;
645    final int mDefParseFlags;
646    final String[] mSeparateProcesses;
647    final boolean mIsUpgrade;
648    final boolean mIsPreNUpgrade;
649    final boolean mIsPreNMR1Upgrade;
650
651    // Have we told the Activity Manager to whitelist the default container service by uid yet?
652    @GuardedBy("mPackages")
653    boolean mDefaultContainerWhitelisted = false;
654
655    @GuardedBy("mPackages")
656    private boolean mDexOptDialogShown;
657
658    /** The location for ASEC container files on internal storage. */
659    final String mAsecInternalPath;
660
661    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
662    // LOCK HELD.  Can be called with mInstallLock held.
663    @GuardedBy("mInstallLock")
664    final Installer mInstaller;
665
666    /** Directory where installed third-party apps stored */
667    final File mAppInstallDir;
668
669    /**
670     * Directory to which applications installed internally have their
671     * 32 bit native libraries copied.
672     */
673    private File mAppLib32InstallDir;
674
675    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
676    // apps.
677    final File mDrmAppPrivateInstallDir;
678
679    // ----------------------------------------------------------------
680
681    // Lock for state used when installing and doing other long running
682    // operations.  Methods that must be called with this lock held have
683    // the suffix "LI".
684    final Object mInstallLock = new Object();
685
686    // ----------------------------------------------------------------
687
688    // Keys are String (package name), values are Package.  This also serves
689    // as the lock for the global state.  Methods that must be called with
690    // this lock held have the prefix "LP".
691    @GuardedBy("mPackages")
692    final ArrayMap<String, PackageParser.Package> mPackages =
693            new ArrayMap<String, PackageParser.Package>();
694
695    final ArrayMap<String, Set<String>> mKnownCodebase =
696            new ArrayMap<String, Set<String>>();
697
698    // Keys are isolated uids and values are the uid of the application
699    // that created the isolated proccess.
700    @GuardedBy("mPackages")
701    final SparseIntArray mIsolatedOwners = new SparseIntArray();
702
703    /**
704     * Tracks new system packages [received in an OTA] that we expect to
705     * find updated user-installed versions. Keys are package name, values
706     * are package location.
707     */
708    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
709    /**
710     * Tracks high priority intent filters for protected actions. During boot, certain
711     * filter actions are protected and should never be allowed to have a high priority
712     * intent filter for them. However, there is one, and only one exception -- the
713     * setup wizard. It must be able to define a high priority intent filter for these
714     * actions to ensure there are no escapes from the wizard. We need to delay processing
715     * of these during boot as we need to look at all of the system packages in order
716     * to know which component is the setup wizard.
717     */
718    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
719    /**
720     * Whether or not processing protected filters should be deferred.
721     */
722    private boolean mDeferProtectedFilters = true;
723
724    /**
725     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
726     */
727    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
728    /**
729     * Whether or not system app permissions should be promoted from install to runtime.
730     */
731    boolean mPromoteSystemApps;
732
733    @GuardedBy("mPackages")
734    final Settings mSettings;
735
736    /**
737     * Set of package names that are currently "frozen", which means active
738     * surgery is being done on the code/data for that package. The platform
739     * will refuse to launch frozen packages to avoid race conditions.
740     *
741     * @see PackageFreezer
742     */
743    @GuardedBy("mPackages")
744    final ArraySet<String> mFrozenPackages = new ArraySet<>();
745
746    final ProtectedPackages mProtectedPackages;
747
748    @GuardedBy("mLoadedVolumes")
749    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
750
751    boolean mFirstBoot;
752
753    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
754
755    // System configuration read by SystemConfig.
756    final int[] mGlobalGids;
757    final SparseArray<ArraySet<String>> mSystemPermissions;
758    @GuardedBy("mAvailableFeatures")
759    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
760
761    // If mac_permissions.xml was found for seinfo labeling.
762    boolean mFoundPolicyFile;
763
764    private final InstantAppRegistry mInstantAppRegistry;
765
766    @GuardedBy("mPackages")
767    int mChangedPackagesSequenceNumber;
768    /**
769     * List of changed [installed, removed or updated] packages.
770     * mapping from user id -> sequence number -> package name
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
774    /**
775     * The sequence number of the last change to a package.
776     * mapping from user id -> package name -> sequence number
777     */
778    @GuardedBy("mPackages")
779    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
780
781    class PackageParserCallback implements PackageParser.Callback {
782        @Override public final boolean hasFeature(String feature) {
783            return PackageManagerService.this.hasSystemFeature(feature, 0);
784        }
785
786        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
787                Collection<PackageParser.Package> allPackages, String targetPackageName) {
788            List<PackageParser.Package> overlayPackages = null;
789            for (PackageParser.Package p : allPackages) {
790                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
791                    if (overlayPackages == null) {
792                        overlayPackages = new ArrayList<PackageParser.Package>();
793                    }
794                    overlayPackages.add(p);
795                }
796            }
797            if (overlayPackages != null) {
798                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
799                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
800                        return p1.mOverlayPriority - p2.mOverlayPriority;
801                    }
802                };
803                Collections.sort(overlayPackages, cmp);
804            }
805            return overlayPackages;
806        }
807
808        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
809                String targetPackageName, String targetPath) {
810            if ("android".equals(targetPackageName)) {
811                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
812                // native AssetManager.
813                return null;
814            }
815            List<PackageParser.Package> overlayPackages =
816                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
817            if (overlayPackages == null || overlayPackages.isEmpty()) {
818                return null;
819            }
820            List<String> overlayPathList = null;
821            for (PackageParser.Package overlayPackage : overlayPackages) {
822                if (targetPath == null) {
823                    if (overlayPathList == null) {
824                        overlayPathList = new ArrayList<String>();
825                    }
826                    overlayPathList.add(overlayPackage.baseCodePath);
827                    continue;
828                }
829
830                try {
831                    // Creates idmaps for system to parse correctly the Android manifest of the
832                    // target package.
833                    //
834                    // OverlayManagerService will update each of them with a correct gid from its
835                    // target package app id.
836                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
837                            UserHandle.getSharedAppGid(
838                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
839                    if (overlayPathList == null) {
840                        overlayPathList = new ArrayList<String>();
841                    }
842                    overlayPathList.add(overlayPackage.baseCodePath);
843                } catch (InstallerException e) {
844                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
845                            overlayPackage.baseCodePath);
846                }
847            }
848            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
849        }
850
851        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
852            synchronized (mPackages) {
853                return getStaticOverlayPathsLocked(
854                        mPackages.values(), targetPackageName, targetPath);
855            }
856        }
857
858        @Override public final String[] getOverlayApks(String targetPackageName) {
859            return getStaticOverlayPaths(targetPackageName, null);
860        }
861
862        @Override public final String[] getOverlayPaths(String targetPackageName,
863                String targetPath) {
864            return getStaticOverlayPaths(targetPackageName, targetPath);
865        }
866    };
867
868    class ParallelPackageParserCallback extends PackageParserCallback {
869        List<PackageParser.Package> mOverlayPackages = null;
870
871        void findStaticOverlayPackages() {
872            synchronized (mPackages) {
873                for (PackageParser.Package p : mPackages.values()) {
874                    if (p.mIsStaticOverlay) {
875                        if (mOverlayPackages == null) {
876                            mOverlayPackages = new ArrayList<PackageParser.Package>();
877                        }
878                        mOverlayPackages.add(p);
879                    }
880                }
881            }
882        }
883
884        @Override
885        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
886            // We can trust mOverlayPackages without holding mPackages because package uninstall
887            // can't happen while running parallel parsing.
888            // Moreover holding mPackages on each parsing thread causes dead-lock.
889            return mOverlayPackages == null ? null :
890                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
891        }
892    }
893
894    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
895    final ParallelPackageParserCallback mParallelPackageParserCallback =
896            new ParallelPackageParserCallback();
897
898    public static final class SharedLibraryEntry {
899        public final @Nullable String path;
900        public final @Nullable String apk;
901        public final @NonNull SharedLibraryInfo info;
902
903        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
904                String declaringPackageName, int declaringPackageVersionCode) {
905            path = _path;
906            apk = _apk;
907            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
908                    declaringPackageName, declaringPackageVersionCode), null);
909        }
910    }
911
912    // Currently known shared libraries.
913    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
914    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
915            new ArrayMap<>();
916
917    // All available activities, for your resolving pleasure.
918    final ActivityIntentResolver mActivities =
919            new ActivityIntentResolver();
920
921    // All available receivers, for your resolving pleasure.
922    final ActivityIntentResolver mReceivers =
923            new ActivityIntentResolver();
924
925    // All available services, for your resolving pleasure.
926    final ServiceIntentResolver mServices = new ServiceIntentResolver();
927
928    // All available providers, for your resolving pleasure.
929    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
930
931    // Mapping from provider base names (first directory in content URI codePath)
932    // to the provider information.
933    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
934            new ArrayMap<String, PackageParser.Provider>();
935
936    // Mapping from instrumentation class names to info about them.
937    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
938            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
939
940    // Mapping from permission names to info about them.
941    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
942            new ArrayMap<String, PackageParser.PermissionGroup>();
943
944    // Packages whose data we have transfered into another package, thus
945    // should no longer exist.
946    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
947
948    // Broadcast actions that are only available to the system.
949    @GuardedBy("mProtectedBroadcasts")
950    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
951
952    /** List of packages waiting for verification. */
953    final SparseArray<PackageVerificationState> mPendingVerification
954            = new SparseArray<PackageVerificationState>();
955
956    /** Set of packages associated with each app op permission. */
957    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
958
959    final PackageInstallerService mInstallerService;
960
961    private final PackageDexOptimizer mPackageDexOptimizer;
962    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
963    // is used by other apps).
964    private final DexManager mDexManager;
965
966    private AtomicInteger mNextMoveId = new AtomicInteger();
967    private final MoveCallbacks mMoveCallbacks;
968
969    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
970
971    // Cache of users who need badging.
972    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
973
974    /** Token for keys in mPendingVerification. */
975    private int mPendingVerificationToken = 0;
976
977    volatile boolean mSystemReady;
978    volatile boolean mSafeMode;
979    volatile boolean mHasSystemUidErrors;
980    private volatile boolean mEphemeralAppsDisabled;
981
982    ApplicationInfo mAndroidApplication;
983    final ActivityInfo mResolveActivity = new ActivityInfo();
984    final ResolveInfo mResolveInfo = new ResolveInfo();
985    ComponentName mResolveComponentName;
986    PackageParser.Package mPlatformPackage;
987    ComponentName mCustomResolverComponentName;
988
989    boolean mResolverReplaced = false;
990
991    private final @Nullable ComponentName mIntentFilterVerifierComponent;
992    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
993
994    private int mIntentFilterVerificationToken = 0;
995
996    /** The service connection to the ephemeral resolver */
997    final EphemeralResolverConnection mInstantAppResolverConnection;
998    /** Component used to show resolver settings for Instant Apps */
999    final ComponentName mInstantAppResolverSettingsComponent;
1000
1001    /** Activity used to install instant applications */
1002    ActivityInfo mInstantAppInstallerActivity;
1003    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1004
1005    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1006            = new SparseArray<IntentFilterVerificationState>();
1007
1008    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1009
1010    // List of packages names to keep cached, even if they are uninstalled for all users
1011    private List<String> mKeepUninstalledPackages;
1012
1013    private UserManagerInternal mUserManagerInternal;
1014
1015    private DeviceIdleController.LocalService mDeviceIdleController;
1016
1017    private File mCacheDir;
1018
1019    private ArraySet<String> mPrivappPermissionsViolations;
1020
1021    private Future<?> mPrepareAppDataFuture;
1022
1023    private static class IFVerificationParams {
1024        PackageParser.Package pkg;
1025        boolean replacing;
1026        int userId;
1027        int verifierUid;
1028
1029        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1030                int _userId, int _verifierUid) {
1031            pkg = _pkg;
1032            replacing = _replacing;
1033            userId = _userId;
1034            replacing = _replacing;
1035            verifierUid = _verifierUid;
1036        }
1037    }
1038
1039    private interface IntentFilterVerifier<T extends IntentFilter> {
1040        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1041                                               T filter, String packageName);
1042        void startVerifications(int userId);
1043        void receiveVerificationResponse(int verificationId);
1044    }
1045
1046    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1047        private Context mContext;
1048        private ComponentName mIntentFilterVerifierComponent;
1049        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1050
1051        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1052            mContext = context;
1053            mIntentFilterVerifierComponent = verifierComponent;
1054        }
1055
1056        private String getDefaultScheme() {
1057            return IntentFilter.SCHEME_HTTPS;
1058        }
1059
1060        @Override
1061        public void startVerifications(int userId) {
1062            // Launch verifications requests
1063            int count = mCurrentIntentFilterVerifications.size();
1064            for (int n=0; n<count; n++) {
1065                int verificationId = mCurrentIntentFilterVerifications.get(n);
1066                final IntentFilterVerificationState ivs =
1067                        mIntentFilterVerificationStates.get(verificationId);
1068
1069                String packageName = ivs.getPackageName();
1070
1071                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1072                final int filterCount = filters.size();
1073                ArraySet<String> domainsSet = new ArraySet<>();
1074                for (int m=0; m<filterCount; m++) {
1075                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1076                    domainsSet.addAll(filter.getHostsList());
1077                }
1078                synchronized (mPackages) {
1079                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1080                            packageName, domainsSet) != null) {
1081                        scheduleWriteSettingsLocked();
1082                    }
1083                }
1084                sendVerificationRequest(verificationId, ivs);
1085            }
1086            mCurrentIntentFilterVerifications.clear();
1087        }
1088
1089        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1090            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1093                    verificationId);
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1096                    getDefaultScheme());
1097            verificationIntent.putExtra(
1098                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1099                    ivs.getHostsString());
1100            verificationIntent.putExtra(
1101                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1102                    ivs.getPackageName());
1103            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1104            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1105
1106            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1107            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1108                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1109                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1110
1111            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1112            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1113                    "Sending IntentFilter verification broadcast");
1114        }
1115
1116        public void receiveVerificationResponse(int verificationId) {
1117            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1118
1119            final boolean verified = ivs.isVerified();
1120
1121            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1122            final int count = filters.size();
1123            if (DEBUG_DOMAIN_VERIFICATION) {
1124                Slog.i(TAG, "Received verification response " + verificationId
1125                        + " for " + count + " filters, verified=" + verified);
1126            }
1127            for (int n=0; n<count; n++) {
1128                PackageParser.ActivityIntentInfo filter = filters.get(n);
1129                filter.setVerified(verified);
1130
1131                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1132                        + " verified with result:" + verified + " and hosts:"
1133                        + ivs.getHostsString());
1134            }
1135
1136            mIntentFilterVerificationStates.remove(verificationId);
1137
1138            final String packageName = ivs.getPackageName();
1139            IntentFilterVerificationInfo ivi = null;
1140
1141            synchronized (mPackages) {
1142                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1143            }
1144            if (ivi == null) {
1145                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1146                        + verificationId + " packageName:" + packageName);
1147                return;
1148            }
1149            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1150                    "Updating IntentFilterVerificationInfo for package " + packageName
1151                            +" verificationId:" + verificationId);
1152
1153            synchronized (mPackages) {
1154                if (verified) {
1155                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1156                } else {
1157                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1158                }
1159                scheduleWriteSettingsLocked();
1160
1161                final int userId = ivs.getUserId();
1162                if (userId != UserHandle.USER_ALL) {
1163                    final int userStatus =
1164                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1165
1166                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1167                    boolean needUpdate = false;
1168
1169                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1170                    // already been set by the User thru the Disambiguation dialog
1171                    switch (userStatus) {
1172                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1173                            if (verified) {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1175                            } else {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1177                            }
1178                            needUpdate = true;
1179                            break;
1180
1181                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1182                            if (verified) {
1183                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1184                                needUpdate = true;
1185                            }
1186                            break;
1187
1188                        default:
1189                            // Nothing to do
1190                    }
1191
1192                    if (needUpdate) {
1193                        mSettings.updateIntentFilterVerificationStatusLPw(
1194                                packageName, updatedStatus, userId);
1195                        scheduleWritePackageRestrictionsLocked(userId);
1196                    }
1197                }
1198            }
1199        }
1200
1201        @Override
1202        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1203                    ActivityIntentInfo filter, String packageName) {
1204            if (!hasValidDomains(filter)) {
1205                return false;
1206            }
1207            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1208            if (ivs == null) {
1209                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1210                        packageName);
1211            }
1212            if (DEBUG_DOMAIN_VERIFICATION) {
1213                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1214            }
1215            ivs.addFilter(filter);
1216            return true;
1217        }
1218
1219        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1220                int userId, int verificationId, String packageName) {
1221            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1222                    verifierUid, userId, packageName);
1223            ivs.setPendingState();
1224            synchronized (mPackages) {
1225                mIntentFilterVerificationStates.append(verificationId, ivs);
1226                mCurrentIntentFilterVerifications.add(verificationId);
1227            }
1228            return ivs;
1229        }
1230    }
1231
1232    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1233        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1234                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1235                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1236    }
1237
1238    // Set of pending broadcasts for aggregating enable/disable of components.
1239    static class PendingPackageBroadcasts {
1240        // for each user id, a map of <package name -> components within that package>
1241        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1242
1243        public PendingPackageBroadcasts() {
1244            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1245        }
1246
1247        public ArrayList<String> get(int userId, String packageName) {
1248            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1249            return packages.get(packageName);
1250        }
1251
1252        public void put(int userId, String packageName, ArrayList<String> components) {
1253            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1254            packages.put(packageName, components);
1255        }
1256
1257        public void remove(int userId, String packageName) {
1258            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1259            if (packages != null) {
1260                packages.remove(packageName);
1261            }
1262        }
1263
1264        public void remove(int userId) {
1265            mUidMap.remove(userId);
1266        }
1267
1268        public int userIdCount() {
1269            return mUidMap.size();
1270        }
1271
1272        public int userIdAt(int n) {
1273            return mUidMap.keyAt(n);
1274        }
1275
1276        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1277            return mUidMap.get(userId);
1278        }
1279
1280        public int size() {
1281            // total number of pending broadcast entries across all userIds
1282            int num = 0;
1283            for (int i = 0; i< mUidMap.size(); i++) {
1284                num += mUidMap.valueAt(i).size();
1285            }
1286            return num;
1287        }
1288
1289        public void clear() {
1290            mUidMap.clear();
1291        }
1292
1293        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1294            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1295            if (map == null) {
1296                map = new ArrayMap<String, ArrayList<String>>();
1297                mUidMap.put(userId, map);
1298            }
1299            return map;
1300        }
1301    }
1302    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1303
1304    // Service Connection to remote media container service to copy
1305    // package uri's from external media onto secure containers
1306    // or internal storage.
1307    private IMediaContainerService mContainerService = null;
1308
1309    static final int SEND_PENDING_BROADCAST = 1;
1310    static final int MCS_BOUND = 3;
1311    static final int END_COPY = 4;
1312    static final int INIT_COPY = 5;
1313    static final int MCS_UNBIND = 6;
1314    static final int START_CLEANING_PACKAGE = 7;
1315    static final int FIND_INSTALL_LOC = 8;
1316    static final int POST_INSTALL = 9;
1317    static final int MCS_RECONNECT = 10;
1318    static final int MCS_GIVE_UP = 11;
1319    static final int UPDATED_MEDIA_STATUS = 12;
1320    static final int WRITE_SETTINGS = 13;
1321    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1322    static final int PACKAGE_VERIFIED = 15;
1323    static final int CHECK_PENDING_VERIFICATION = 16;
1324    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1325    static final int INTENT_FILTER_VERIFIED = 18;
1326    static final int WRITE_PACKAGE_LIST = 19;
1327    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1328
1329    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1330
1331    // Delay time in millisecs
1332    static final int BROADCAST_DELAY = 10 * 1000;
1333
1334    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1335            2 * 60 * 60 * 1000L; /* two hours */
1336
1337    static UserManagerService sUserManager;
1338
1339    // Stores a list of users whose package restrictions file needs to be updated
1340    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1341
1342    final private DefaultContainerConnection mDefContainerConn =
1343            new DefaultContainerConnection();
1344    class DefaultContainerConnection implements ServiceConnection {
1345        public void onServiceConnected(ComponentName name, IBinder service) {
1346            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1347            final IMediaContainerService imcs = IMediaContainerService.Stub
1348                    .asInterface(Binder.allowBlocking(service));
1349            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1350        }
1351
1352        public void onServiceDisconnected(ComponentName name) {
1353            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1354        }
1355    }
1356
1357    // Recordkeeping of restore-after-install operations that are currently in flight
1358    // between the Package Manager and the Backup Manager
1359    static class PostInstallData {
1360        public InstallArgs args;
1361        public PackageInstalledInfo res;
1362
1363        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1364            args = _a;
1365            res = _r;
1366        }
1367    }
1368
1369    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1370    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1371
1372    // XML tags for backup/restore of various bits of state
1373    private static final String TAG_PREFERRED_BACKUP = "pa";
1374    private static final String TAG_DEFAULT_APPS = "da";
1375    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1376
1377    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1378    private static final String TAG_ALL_GRANTS = "rt-grants";
1379    private static final String TAG_GRANT = "grant";
1380    private static final String ATTR_PACKAGE_NAME = "pkg";
1381
1382    private static final String TAG_PERMISSION = "perm";
1383    private static final String ATTR_PERMISSION_NAME = "name";
1384    private static final String ATTR_IS_GRANTED = "g";
1385    private static final String ATTR_USER_SET = "set";
1386    private static final String ATTR_USER_FIXED = "fixed";
1387    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1388
1389    // System/policy permission grants are not backed up
1390    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1391            FLAG_PERMISSION_POLICY_FIXED
1392            | FLAG_PERMISSION_SYSTEM_FIXED
1393            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1394
1395    // And we back up these user-adjusted states
1396    private static final int USER_RUNTIME_GRANT_MASK =
1397            FLAG_PERMISSION_USER_SET
1398            | FLAG_PERMISSION_USER_FIXED
1399            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1400
1401    final @Nullable String mRequiredVerifierPackage;
1402    final @NonNull String mRequiredInstallerPackage;
1403    final @NonNull String mRequiredUninstallerPackage;
1404    final @Nullable String mSetupWizardPackage;
1405    final @Nullable String mStorageManagerPackage;
1406    final @NonNull String mServicesSystemSharedLibraryPackageName;
1407    final @NonNull String mSharedSystemSharedLibraryPackageName;
1408
1409    final boolean mPermissionReviewRequired;
1410
1411    private final PackageUsage mPackageUsage = new PackageUsage();
1412    private final CompilerStats mCompilerStats = new CompilerStats();
1413
1414    class PackageHandler extends Handler {
1415        private boolean mBound = false;
1416        final ArrayList<HandlerParams> mPendingInstalls =
1417            new ArrayList<HandlerParams>();
1418
1419        private boolean connectToService() {
1420            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1421                    " DefaultContainerService");
1422            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1425                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1426                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427                mBound = true;
1428                return true;
1429            }
1430            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1431            return false;
1432        }
1433
1434        private void disconnectService() {
1435            mContainerService = null;
1436            mBound = false;
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1438            mContext.unbindService(mDefContainerConn);
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1440        }
1441
1442        PackageHandler(Looper looper) {
1443            super(looper);
1444        }
1445
1446        public void handleMessage(Message msg) {
1447            try {
1448                doHandleMessage(msg);
1449            } finally {
1450                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1451            }
1452        }
1453
1454        void doHandleMessage(Message msg) {
1455            switch (msg.what) {
1456                case INIT_COPY: {
1457                    HandlerParams params = (HandlerParams) msg.obj;
1458                    int idx = mPendingInstalls.size();
1459                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1460                    // If a bind was already initiated we dont really
1461                    // need to do anything. The pending install
1462                    // will be processed later on.
1463                    if (!mBound) {
1464                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1465                                System.identityHashCode(mHandler));
1466                        // If this is the only one pending we might
1467                        // have to bind to the service again.
1468                        if (!connectToService()) {
1469                            Slog.e(TAG, "Failed to bind to media container service");
1470                            params.serviceError();
1471                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1472                                    System.identityHashCode(mHandler));
1473                            if (params.traceMethod != null) {
1474                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1475                                        params.traceCookie);
1476                            }
1477                            return;
1478                        } else {
1479                            // Once we bind to the service, the first
1480                            // pending request will be processed.
1481                            mPendingInstalls.add(idx, params);
1482                        }
1483                    } else {
1484                        mPendingInstalls.add(idx, params);
1485                        // Already bound to the service. Just make
1486                        // sure we trigger off processing the first request.
1487                        if (idx == 0) {
1488                            mHandler.sendEmptyMessage(MCS_BOUND);
1489                        }
1490                    }
1491                    break;
1492                }
1493                case MCS_BOUND: {
1494                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1495                    if (msg.obj != null) {
1496                        mContainerService = (IMediaContainerService) msg.obj;
1497                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1498                                System.identityHashCode(mHandler));
1499                    }
1500                    if (mContainerService == null) {
1501                        if (!mBound) {
1502                            // Something seriously wrong since we are not bound and we are not
1503                            // waiting for connection. Bail out.
1504                            Slog.e(TAG, "Cannot bind to media container service");
1505                            for (HandlerParams params : mPendingInstalls) {
1506                                // Indicate service bind error
1507                                params.serviceError();
1508                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                        System.identityHashCode(params));
1510                                if (params.traceMethod != null) {
1511                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1512                                            params.traceMethod, params.traceCookie);
1513                                }
1514                                return;
1515                            }
1516                            mPendingInstalls.clear();
1517                        } else {
1518                            Slog.w(TAG, "Waiting to connect to media container service");
1519                        }
1520                    } else if (mPendingInstalls.size() > 0) {
1521                        HandlerParams params = mPendingInstalls.get(0);
1522                        if (params != null) {
1523                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1524                                    System.identityHashCode(params));
1525                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1526                            if (params.startCopy()) {
1527                                // We are done...  look for more work or to
1528                                // go idle.
1529                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1530                                        "Checking for more work or unbind...");
1531                                // Delete pending install
1532                                if (mPendingInstalls.size() > 0) {
1533                                    mPendingInstalls.remove(0);
1534                                }
1535                                if (mPendingInstalls.size() == 0) {
1536                                    if (mBound) {
1537                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1538                                                "Posting delayed MCS_UNBIND");
1539                                        removeMessages(MCS_UNBIND);
1540                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1541                                        // Unbind after a little delay, to avoid
1542                                        // continual thrashing.
1543                                        sendMessageDelayed(ubmsg, 10000);
1544                                    }
1545                                } else {
1546                                    // There are more pending requests in queue.
1547                                    // Just post MCS_BOUND message to trigger processing
1548                                    // of next pending install.
1549                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1550                                            "Posting MCS_BOUND for next work");
1551                                    mHandler.sendEmptyMessage(MCS_BOUND);
1552                                }
1553                            }
1554                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1555                        }
1556                    } else {
1557                        // Should never happen ideally.
1558                        Slog.w(TAG, "Empty queue");
1559                    }
1560                    break;
1561                }
1562                case MCS_RECONNECT: {
1563                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1564                    if (mPendingInstalls.size() > 0) {
1565                        if (mBound) {
1566                            disconnectService();
1567                        }
1568                        if (!connectToService()) {
1569                            Slog.e(TAG, "Failed to bind to media container service");
1570                            for (HandlerParams params : mPendingInstalls) {
1571                                // Indicate service bind error
1572                                params.serviceError();
1573                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1574                                        System.identityHashCode(params));
1575                            }
1576                            mPendingInstalls.clear();
1577                        }
1578                    }
1579                    break;
1580                }
1581                case MCS_UNBIND: {
1582                    // If there is no actual work left, then time to unbind.
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1584
1585                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1586                        if (mBound) {
1587                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1588
1589                            disconnectService();
1590                        }
1591                    } else if (mPendingInstalls.size() > 0) {
1592                        // There are more pending requests in queue.
1593                        // Just post MCS_BOUND message to trigger processing
1594                        // of next pending install.
1595                        mHandler.sendEmptyMessage(MCS_BOUND);
1596                    }
1597
1598                    break;
1599                }
1600                case MCS_GIVE_UP: {
1601                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1602                    HandlerParams params = mPendingInstalls.remove(0);
1603                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1604                            System.identityHashCode(params));
1605                    break;
1606                }
1607                case SEND_PENDING_BROADCAST: {
1608                    String packages[];
1609                    ArrayList<String> components[];
1610                    int size = 0;
1611                    int uids[];
1612                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1613                    synchronized (mPackages) {
1614                        if (mPendingBroadcasts == null) {
1615                            return;
1616                        }
1617                        size = mPendingBroadcasts.size();
1618                        if (size <= 0) {
1619                            // Nothing to be done. Just return
1620                            return;
1621                        }
1622                        packages = new String[size];
1623                        components = new ArrayList[size];
1624                        uids = new int[size];
1625                        int i = 0;  // filling out the above arrays
1626
1627                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1628                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1629                            Iterator<Map.Entry<String, ArrayList<String>>> it
1630                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1631                                            .entrySet().iterator();
1632                            while (it.hasNext() && i < size) {
1633                                Map.Entry<String, ArrayList<String>> ent = it.next();
1634                                packages[i] = ent.getKey();
1635                                components[i] = ent.getValue();
1636                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1637                                uids[i] = (ps != null)
1638                                        ? UserHandle.getUid(packageUserId, ps.appId)
1639                                        : -1;
1640                                i++;
1641                            }
1642                        }
1643                        size = i;
1644                        mPendingBroadcasts.clear();
1645                    }
1646                    // Send broadcasts
1647                    for (int i = 0; i < size; i++) {
1648                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1649                    }
1650                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1651                    break;
1652                }
1653                case START_CLEANING_PACKAGE: {
1654                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1655                    final String packageName = (String)msg.obj;
1656                    final int userId = msg.arg1;
1657                    final boolean andCode = msg.arg2 != 0;
1658                    synchronized (mPackages) {
1659                        if (userId == UserHandle.USER_ALL) {
1660                            int[] users = sUserManager.getUserIds();
1661                            for (int user : users) {
1662                                mSettings.addPackageToCleanLPw(
1663                                        new PackageCleanItem(user, packageName, andCode));
1664                            }
1665                        } else {
1666                            mSettings.addPackageToCleanLPw(
1667                                    new PackageCleanItem(userId, packageName, andCode));
1668                        }
1669                    }
1670                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1671                    startCleaningPackages();
1672                } break;
1673                case POST_INSTALL: {
1674                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1675
1676                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1677                    final boolean didRestore = (msg.arg2 != 0);
1678                    mRunningInstalls.delete(msg.arg1);
1679
1680                    if (data != null) {
1681                        InstallArgs args = data.args;
1682                        PackageInstalledInfo parentRes = data.res;
1683
1684                        final boolean grantPermissions = (args.installFlags
1685                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1686                        final boolean killApp = (args.installFlags
1687                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1688                        final boolean virtualPreload = ((args.installFlags
1689                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1690                        final String[] grantedPermissions = args.installGrantPermissions;
1691
1692                        // Handle the parent package
1693                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1694                                virtualPreload, grantedPermissions, didRestore,
1695                                args.installerPackageName, args.observer);
1696
1697                        // Handle the child packages
1698                        final int childCount = (parentRes.addedChildPackages != null)
1699                                ? parentRes.addedChildPackages.size() : 0;
1700                        for (int i = 0; i < childCount; i++) {
1701                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1702                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1703                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1704                                    args.installerPackageName, args.observer);
1705                        }
1706
1707                        // Log tracing if needed
1708                        if (args.traceMethod != null) {
1709                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1710                                    args.traceCookie);
1711                        }
1712                    } else {
1713                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1714                    }
1715
1716                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1717                } break;
1718                case UPDATED_MEDIA_STATUS: {
1719                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1720                    boolean reportStatus = msg.arg1 == 1;
1721                    boolean doGc = msg.arg2 == 1;
1722                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1723                    if (doGc) {
1724                        // Force a gc to clear up stale containers.
1725                        Runtime.getRuntime().gc();
1726                    }
1727                    if (msg.obj != null) {
1728                        @SuppressWarnings("unchecked")
1729                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1730                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1731                        // Unload containers
1732                        unloadAllContainers(args);
1733                    }
1734                    if (reportStatus) {
1735                        try {
1736                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1737                                    "Invoking StorageManagerService call back");
1738                            PackageHelper.getStorageManager().finishMediaUpdate();
1739                        } catch (RemoteException e) {
1740                            Log.e(TAG, "StorageManagerService not running?");
1741                        }
1742                    }
1743                } break;
1744                case WRITE_SETTINGS: {
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1746                    synchronized (mPackages) {
1747                        removeMessages(WRITE_SETTINGS);
1748                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1749                        mSettings.writeLPr();
1750                        mDirtyUsers.clear();
1751                    }
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1753                } break;
1754                case WRITE_PACKAGE_RESTRICTIONS: {
1755                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1756                    synchronized (mPackages) {
1757                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1758                        for (int userId : mDirtyUsers) {
1759                            mSettings.writePackageRestrictionsLPr(userId);
1760                        }
1761                        mDirtyUsers.clear();
1762                    }
1763                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1764                } break;
1765                case WRITE_PACKAGE_LIST: {
1766                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1767                    synchronized (mPackages) {
1768                        removeMessages(WRITE_PACKAGE_LIST);
1769                        mSettings.writePackageListLPr(msg.arg1);
1770                    }
1771                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1772                } break;
1773                case CHECK_PENDING_VERIFICATION: {
1774                    final int verificationId = msg.arg1;
1775                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1776
1777                    if ((state != null) && !state.timeoutExtended()) {
1778                        final InstallArgs args = state.getInstallArgs();
1779                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1780
1781                        Slog.i(TAG, "Verification timed out for " + originUri);
1782                        mPendingVerification.remove(verificationId);
1783
1784                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1785
1786                        final UserHandle user = args.getUser();
1787                        if (getDefaultVerificationResponse(user)
1788                                == PackageManager.VERIFICATION_ALLOW) {
1789                            Slog.i(TAG, "Continuing with installation of " + originUri);
1790                            state.setVerifierResponse(Binder.getCallingUid(),
1791                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1792                            broadcastPackageVerified(verificationId, originUri,
1793                                    PackageManager.VERIFICATION_ALLOW, user);
1794                            try {
1795                                ret = args.copyApk(mContainerService, true);
1796                            } catch (RemoteException e) {
1797                                Slog.e(TAG, "Could not contact the ContainerService");
1798                            }
1799                        } else {
1800                            broadcastPackageVerified(verificationId, originUri,
1801                                    PackageManager.VERIFICATION_REJECT, user);
1802                        }
1803
1804                        Trace.asyncTraceEnd(
1805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806
1807                        processPendingInstall(args, ret);
1808                        mHandler.sendEmptyMessage(MCS_UNBIND);
1809                    }
1810                    break;
1811                }
1812                case PACKAGE_VERIFIED: {
1813                    final int verificationId = msg.arg1;
1814
1815                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1816                    if (state == null) {
1817                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1818                        break;
1819                    }
1820
1821                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1822
1823                    state.setVerifierResponse(response.callerUid, response.code);
1824
1825                    if (state.isVerificationComplete()) {
1826                        mPendingVerification.remove(verificationId);
1827
1828                        final InstallArgs args = state.getInstallArgs();
1829                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1830
1831                        int ret;
1832                        if (state.isInstallAllowed()) {
1833                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1834                            broadcastPackageVerified(verificationId, originUri,
1835                                    response.code, state.getInstallArgs().getUser());
1836                            try {
1837                                ret = args.copyApk(mContainerService, true);
1838                            } catch (RemoteException e) {
1839                                Slog.e(TAG, "Could not contact the ContainerService");
1840                            }
1841                        } else {
1842                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1843                        }
1844
1845                        Trace.asyncTraceEnd(
1846                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1847
1848                        processPendingInstall(args, ret);
1849                        mHandler.sendEmptyMessage(MCS_UNBIND);
1850                    }
1851
1852                    break;
1853                }
1854                case START_INTENT_FILTER_VERIFICATIONS: {
1855                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1856                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1857                            params.replacing, params.pkg);
1858                    break;
1859                }
1860                case INTENT_FILTER_VERIFIED: {
1861                    final int verificationId = msg.arg1;
1862
1863                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1864                            verificationId);
1865                    if (state == null) {
1866                        Slog.w(TAG, "Invalid IntentFilter verification token "
1867                                + verificationId + " received");
1868                        break;
1869                    }
1870
1871                    final int userId = state.getUserId();
1872
1873                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1874                            "Processing IntentFilter verification with token:"
1875                            + verificationId + " and userId:" + userId);
1876
1877                    final IntentFilterVerificationResponse response =
1878                            (IntentFilterVerificationResponse) msg.obj;
1879
1880                    state.setVerifierResponse(response.callerUid, response.code);
1881
1882                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1883                            "IntentFilter verification with token:" + verificationId
1884                            + " and userId:" + userId
1885                            + " is settings verifier response with response code:"
1886                            + response.code);
1887
1888                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1889                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1890                                + response.getFailedDomainsString());
1891                    }
1892
1893                    if (state.isVerificationComplete()) {
1894                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1895                    } else {
1896                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1897                                "IntentFilter verification with token:" + verificationId
1898                                + " was not said to be complete");
1899                    }
1900
1901                    break;
1902                }
1903                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1904                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1905                            mInstantAppResolverConnection,
1906                            (InstantAppRequest) msg.obj,
1907                            mInstantAppInstallerActivity,
1908                            mHandler);
1909                }
1910            }
1911        }
1912    }
1913
1914    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1915            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1916            boolean launchedForRestore, String installerPackage,
1917            IPackageInstallObserver2 installObserver) {
1918        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1919            // Send the removed broadcasts
1920            if (res.removedInfo != null) {
1921                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1922            }
1923
1924            // Now that we successfully installed the package, grant runtime
1925            // permissions if requested before broadcasting the install. Also
1926            // for legacy apps in permission review mode we clear the permission
1927            // review flag which is used to emulate runtime permissions for
1928            // legacy apps.
1929            if (grantPermissions) {
1930                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1931            }
1932
1933            final boolean update = res.removedInfo != null
1934                    && res.removedInfo.removedPackage != null;
1935            final String installerPackageName =
1936                    res.installerPackageName != null
1937                            ? res.installerPackageName
1938                            : res.removedInfo != null
1939                                    ? res.removedInfo.installerPackageName
1940                                    : null;
1941
1942            // If this is the first time we have child packages for a disabled privileged
1943            // app that had no children, we grant requested runtime permissions to the new
1944            // children if the parent on the system image had them already granted.
1945            if (res.pkg.parentPackage != null) {
1946                synchronized (mPackages) {
1947                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1948                }
1949            }
1950
1951            synchronized (mPackages) {
1952                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1953            }
1954
1955            final String packageName = res.pkg.applicationInfo.packageName;
1956
1957            // Determine the set of users who are adding this package for
1958            // the first time vs. those who are seeing an update.
1959            int[] firstUsers = EMPTY_INT_ARRAY;
1960            int[] updateUsers = EMPTY_INT_ARRAY;
1961            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1962            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1963            for (int newUser : res.newUsers) {
1964                if (ps.getInstantApp(newUser)) {
1965                    continue;
1966                }
1967                if (allNewUsers) {
1968                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1969                    continue;
1970                }
1971                boolean isNew = true;
1972                for (int origUser : res.origUsers) {
1973                    if (origUser == newUser) {
1974                        isNew = false;
1975                        break;
1976                    }
1977                }
1978                if (isNew) {
1979                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1980                } else {
1981                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1982                }
1983            }
1984
1985            // Send installed broadcasts if the package is not a static shared lib.
1986            if (res.pkg.staticSharedLibName == null) {
1987                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1988
1989                // Send added for users that see the package for the first time
1990                // sendPackageAddedForNewUsers also deals with system apps
1991                int appId = UserHandle.getAppId(res.uid);
1992                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1993                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1994                        virtualPreload /*startReceiver*/, appId, firstUsers);
1995
1996                // Send added for users that don't see the package for the first time
1997                Bundle extras = new Bundle(1);
1998                extras.putInt(Intent.EXTRA_UID, res.uid);
1999                if (update) {
2000                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2001                }
2002                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2003                        extras, 0 /*flags*/,
2004                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2005                if (installerPackageName != null) {
2006                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2007                            extras, 0 /*flags*/,
2008                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2009                }
2010
2011                // Send replaced for users that don't see the package for the first time
2012                if (update) {
2013                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2014                            packageName, extras, 0 /*flags*/,
2015                            null /*targetPackage*/, null /*finishedReceiver*/,
2016                            updateUsers);
2017                    if (installerPackageName != null) {
2018                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2019                                extras, 0 /*flags*/,
2020                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2021                    }
2022                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2023                            null /*package*/, null /*extras*/, 0 /*flags*/,
2024                            packageName /*targetPackage*/,
2025                            null /*finishedReceiver*/, updateUsers);
2026                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2027                    // First-install and we did a restore, so we're responsible for the
2028                    // first-launch broadcast.
2029                    if (DEBUG_BACKUP) {
2030                        Slog.i(TAG, "Post-restore of " + packageName
2031                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2032                    }
2033                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2034                }
2035
2036                // Send broadcast package appeared if forward locked/external for all users
2037                // treat asec-hosted packages like removable media on upgrade
2038                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2039                    if (DEBUG_INSTALL) {
2040                        Slog.i(TAG, "upgrading pkg " + res.pkg
2041                                + " is ASEC-hosted -> AVAILABLE");
2042                    }
2043                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2044                    ArrayList<String> pkgList = new ArrayList<>(1);
2045                    pkgList.add(packageName);
2046                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2047                }
2048            }
2049
2050            // Work that needs to happen on first install within each user
2051            if (firstUsers != null && firstUsers.length > 0) {
2052                synchronized (mPackages) {
2053                    for (int userId : firstUsers) {
2054                        // If this app is a browser and it's newly-installed for some
2055                        // users, clear any default-browser state in those users. The
2056                        // app's nature doesn't depend on the user, so we can just check
2057                        // its browser nature in any user and generalize.
2058                        if (packageIsBrowser(packageName, userId)) {
2059                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2060                        }
2061
2062                        // We may also need to apply pending (restored) runtime
2063                        // permission grants within these users.
2064                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2065                    }
2066                }
2067            }
2068
2069            // Log current value of "unknown sources" setting
2070            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2071                    getUnknownSourcesSettings());
2072
2073            // Remove the replaced package's older resources safely now
2074            // We delete after a gc for applications  on sdcard.
2075            if (res.removedInfo != null && res.removedInfo.args != null) {
2076                Runtime.getRuntime().gc();
2077                synchronized (mInstallLock) {
2078                    res.removedInfo.args.doPostDeleteLI(true);
2079                }
2080            } else {
2081                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2082                // and not block here.
2083                VMRuntime.getRuntime().requestConcurrentGC();
2084            }
2085
2086            // Notify DexManager that the package was installed for new users.
2087            // The updated users should already be indexed and the package code paths
2088            // should not change.
2089            // Don't notify the manager for ephemeral apps as they are not expected to
2090            // survive long enough to benefit of background optimizations.
2091            for (int userId : firstUsers) {
2092                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2093                // There's a race currently where some install events may interleave with an uninstall.
2094                // This can lead to package info being null (b/36642664).
2095                if (info != null) {
2096                    mDexManager.notifyPackageInstalled(info, userId);
2097                }
2098            }
2099        }
2100
2101        // If someone is watching installs - notify them
2102        if (installObserver != null) {
2103            try {
2104                Bundle extras = extrasForInstallResult(res);
2105                installObserver.onPackageInstalled(res.name, res.returnCode,
2106                        res.returnMsg, extras);
2107            } catch (RemoteException e) {
2108                Slog.i(TAG, "Observer no longer exists.");
2109            }
2110        }
2111    }
2112
2113    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2114            PackageParser.Package pkg) {
2115        if (pkg.parentPackage == null) {
2116            return;
2117        }
2118        if (pkg.requestedPermissions == null) {
2119            return;
2120        }
2121        final PackageSetting disabledSysParentPs = mSettings
2122                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2123        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2124                || !disabledSysParentPs.isPrivileged()
2125                || (disabledSysParentPs.childPackageNames != null
2126                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2127            return;
2128        }
2129        final int[] allUserIds = sUserManager.getUserIds();
2130        final int permCount = pkg.requestedPermissions.size();
2131        for (int i = 0; i < permCount; i++) {
2132            String permission = pkg.requestedPermissions.get(i);
2133            BasePermission bp = mSettings.mPermissions.get(permission);
2134            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2135                continue;
2136            }
2137            for (int userId : allUserIds) {
2138                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2139                        permission, userId)) {
2140                    grantRuntimePermission(pkg.packageName, permission, userId);
2141                }
2142            }
2143        }
2144    }
2145
2146    private StorageEventListener mStorageListener = new StorageEventListener() {
2147        @Override
2148        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2149            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2150                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2151                    final String volumeUuid = vol.getFsUuid();
2152
2153                    // Clean up any users or apps that were removed or recreated
2154                    // while this volume was missing
2155                    sUserManager.reconcileUsers(volumeUuid);
2156                    reconcileApps(volumeUuid);
2157
2158                    // Clean up any install sessions that expired or were
2159                    // cancelled while this volume was missing
2160                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2161
2162                    loadPrivatePackages(vol);
2163
2164                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2165                    unloadPrivatePackages(vol);
2166                }
2167            }
2168
2169            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2170                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2171                    updateExternalMediaStatus(true, false);
2172                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2173                    updateExternalMediaStatus(false, false);
2174                }
2175            }
2176        }
2177
2178        @Override
2179        public void onVolumeForgotten(String fsUuid) {
2180            if (TextUtils.isEmpty(fsUuid)) {
2181                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2182                return;
2183            }
2184
2185            // Remove any apps installed on the forgotten volume
2186            synchronized (mPackages) {
2187                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2188                for (PackageSetting ps : packages) {
2189                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2190                    deletePackageVersioned(new VersionedPackage(ps.name,
2191                            PackageManager.VERSION_CODE_HIGHEST),
2192                            new LegacyPackageDeleteObserver(null).getBinder(),
2193                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2194                    // Try very hard to release any references to this package
2195                    // so we don't risk the system server being killed due to
2196                    // open FDs
2197                    AttributeCache.instance().removePackage(ps.name);
2198                }
2199
2200                mSettings.onVolumeForgotten(fsUuid);
2201                mSettings.writeLPr();
2202            }
2203        }
2204    };
2205
2206    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2207            String[] grantedPermissions) {
2208        for (int userId : userIds) {
2209            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2210        }
2211    }
2212
2213    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2214            String[] grantedPermissions) {
2215        PackageSetting ps = (PackageSetting) pkg.mExtras;
2216        if (ps == null) {
2217            return;
2218        }
2219
2220        PermissionsState permissionsState = ps.getPermissionsState();
2221
2222        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2223                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2224
2225        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2226                >= Build.VERSION_CODES.M;
2227
2228        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2229
2230        for (String permission : pkg.requestedPermissions) {
2231            final BasePermission bp;
2232            synchronized (mPackages) {
2233                bp = mSettings.mPermissions.get(permission);
2234            }
2235            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2236                    && (!instantApp || bp.isInstant())
2237                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2238                    && (grantedPermissions == null
2239                           || ArrayUtils.contains(grantedPermissions, permission))) {
2240                final int flags = permissionsState.getPermissionFlags(permission, userId);
2241                if (supportsRuntimePermissions) {
2242                    // Installer cannot change immutable permissions.
2243                    if ((flags & immutableFlags) == 0) {
2244                        grantRuntimePermission(pkg.packageName, permission, userId);
2245                    }
2246                } else if (mPermissionReviewRequired) {
2247                    // In permission review mode we clear the review flag when we
2248                    // are asked to install the app with all permissions granted.
2249                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2250                        updatePermissionFlags(permission, pkg.packageName,
2251                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2252                    }
2253                }
2254            }
2255        }
2256    }
2257
2258    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2259        Bundle extras = null;
2260        switch (res.returnCode) {
2261            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2262                extras = new Bundle();
2263                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2264                        res.origPermission);
2265                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2266                        res.origPackage);
2267                break;
2268            }
2269            case PackageManager.INSTALL_SUCCEEDED: {
2270                extras = new Bundle();
2271                extras.putBoolean(Intent.EXTRA_REPLACING,
2272                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2273                break;
2274            }
2275        }
2276        return extras;
2277    }
2278
2279    void scheduleWriteSettingsLocked() {
2280        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2281            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2282        }
2283    }
2284
2285    void scheduleWritePackageListLocked(int userId) {
2286        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2287            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2288            msg.arg1 = userId;
2289            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2290        }
2291    }
2292
2293    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2294        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2295        scheduleWritePackageRestrictionsLocked(userId);
2296    }
2297
2298    void scheduleWritePackageRestrictionsLocked(int userId) {
2299        final int[] userIds = (userId == UserHandle.USER_ALL)
2300                ? sUserManager.getUserIds() : new int[]{userId};
2301        for (int nextUserId : userIds) {
2302            if (!sUserManager.exists(nextUserId)) return;
2303            mDirtyUsers.add(nextUserId);
2304            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2305                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2306            }
2307        }
2308    }
2309
2310    public static PackageManagerService main(Context context, Installer installer,
2311            boolean factoryTest, boolean onlyCore) {
2312        // Self-check for initial settings.
2313        PackageManagerServiceCompilerMapping.checkProperties();
2314
2315        PackageManagerService m = new PackageManagerService(context, installer,
2316                factoryTest, onlyCore);
2317        m.enableSystemUserPackages();
2318        ServiceManager.addService("package", m);
2319        final PackageManagerNative pmn = m.new PackageManagerNative();
2320        ServiceManager.addService("package_native", pmn);
2321        return m;
2322    }
2323
2324    private void enableSystemUserPackages() {
2325        if (!UserManager.isSplitSystemUser()) {
2326            return;
2327        }
2328        // For system user, enable apps based on the following conditions:
2329        // - app is whitelisted or belong to one of these groups:
2330        //   -- system app which has no launcher icons
2331        //   -- system app which has INTERACT_ACROSS_USERS permission
2332        //   -- system IME app
2333        // - app is not in the blacklist
2334        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2335        Set<String> enableApps = new ArraySet<>();
2336        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2337                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2338                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2339        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2340        enableApps.addAll(wlApps);
2341        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2342                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2343        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2344        enableApps.removeAll(blApps);
2345        Log.i(TAG, "Applications installed for system user: " + enableApps);
2346        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2347                UserHandle.SYSTEM);
2348        final int allAppsSize = allAps.size();
2349        synchronized (mPackages) {
2350            for (int i = 0; i < allAppsSize; i++) {
2351                String pName = allAps.get(i);
2352                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2353                // Should not happen, but we shouldn't be failing if it does
2354                if (pkgSetting == null) {
2355                    continue;
2356                }
2357                boolean install = enableApps.contains(pName);
2358                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2359                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2360                            + " for system user");
2361                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2362                }
2363            }
2364            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2365        }
2366    }
2367
2368    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2369        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2370                Context.DISPLAY_SERVICE);
2371        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2372    }
2373
2374    /**
2375     * Requests that files preopted on a secondary system partition be copied to the data partition
2376     * if possible.  Note that the actual copying of the files is accomplished by init for security
2377     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2378     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2379     */
2380    private static void requestCopyPreoptedFiles() {
2381        final int WAIT_TIME_MS = 100;
2382        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2383        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2384            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2385            // We will wait for up to 100 seconds.
2386            final long timeStart = SystemClock.uptimeMillis();
2387            final long timeEnd = timeStart + 100 * 1000;
2388            long timeNow = timeStart;
2389            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2390                try {
2391                    Thread.sleep(WAIT_TIME_MS);
2392                } catch (InterruptedException e) {
2393                    // Do nothing
2394                }
2395                timeNow = SystemClock.uptimeMillis();
2396                if (timeNow > timeEnd) {
2397                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2398                    Slog.wtf(TAG, "cppreopt did not finish!");
2399                    break;
2400                }
2401            }
2402
2403            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2404        }
2405    }
2406
2407    public PackageManagerService(Context context, Installer installer,
2408            boolean factoryTest, boolean onlyCore) {
2409        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2410        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2411        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2412                SystemClock.uptimeMillis());
2413
2414        if (mSdkVersion <= 0) {
2415            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2416        }
2417
2418        mContext = context;
2419
2420        mPermissionReviewRequired = context.getResources().getBoolean(
2421                R.bool.config_permissionReviewRequired);
2422
2423        mFactoryTest = factoryTest;
2424        mOnlyCore = onlyCore;
2425        mMetrics = new DisplayMetrics();
2426        mSettings = new Settings(mPackages);
2427        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439
2440        String separateProcesses = SystemProperties.get("debug.separate_processes");
2441        if (separateProcesses != null && separateProcesses.length() > 0) {
2442            if ("*".equals(separateProcesses)) {
2443                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2444                mSeparateProcesses = null;
2445                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2446            } else {
2447                mDefParseFlags = 0;
2448                mSeparateProcesses = separateProcesses.split(",");
2449                Slog.w(TAG, "Running with debug.separate_processes: "
2450                        + separateProcesses);
2451            }
2452        } else {
2453            mDefParseFlags = 0;
2454            mSeparateProcesses = null;
2455        }
2456
2457        mInstaller = installer;
2458        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2459                "*dexopt*");
2460        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2461        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2462
2463        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2464                FgThread.get().getLooper());
2465
2466        getDefaultDisplayMetrics(context, mMetrics);
2467
2468        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2469        SystemConfig systemConfig = SystemConfig.getInstance();
2470        mGlobalGids = systemConfig.getGlobalGids();
2471        mSystemPermissions = systemConfig.getSystemPermissions();
2472        mAvailableFeatures = systemConfig.getAvailableFeatures();
2473        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2474
2475        mProtectedPackages = new ProtectedPackages(mContext);
2476
2477        synchronized (mInstallLock) {
2478        // writer
2479        synchronized (mPackages) {
2480            mHandlerThread = new ServiceThread(TAG,
2481                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2482            mHandlerThread.start();
2483            mHandler = new PackageHandler(mHandlerThread.getLooper());
2484            mProcessLoggingHandler = new ProcessLoggingHandler();
2485            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2486
2487            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2488            mInstantAppRegistry = new InstantAppRegistry(this);
2489
2490            File dataDir = Environment.getDataDirectory();
2491            mAppInstallDir = new File(dataDir, "app");
2492            mAppLib32InstallDir = new File(dataDir, "app-lib");
2493            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2494            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2495            sUserManager = new UserManagerService(context, this,
2496                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2497
2498            // Propagate permission configuration in to package manager.
2499            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2500                    = systemConfig.getPermissions();
2501            for (int i=0; i<permConfig.size(); i++) {
2502                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2503                BasePermission bp = mSettings.mPermissions.get(perm.name);
2504                if (bp == null) {
2505                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2506                    mSettings.mPermissions.put(perm.name, bp);
2507                }
2508                if (perm.gids != null) {
2509                    bp.setGids(perm.gids, perm.perUser);
2510                }
2511            }
2512
2513            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2514            final int builtInLibCount = libConfig.size();
2515            for (int i = 0; i < builtInLibCount; i++) {
2516                String name = libConfig.keyAt(i);
2517                String path = libConfig.valueAt(i);
2518                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2519                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2520            }
2521
2522            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2523
2524            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2525            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2526            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2527
2528            // Clean up orphaned packages for which the code path doesn't exist
2529            // and they are an update to a system app - caused by bug/32321269
2530            final int packageSettingCount = mSettings.mPackages.size();
2531            for (int i = packageSettingCount - 1; i >= 0; i--) {
2532                PackageSetting ps = mSettings.mPackages.valueAt(i);
2533                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2534                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2535                    mSettings.mPackages.removeAt(i);
2536                    mSettings.enableSystemPackageLPw(ps.name);
2537                }
2538            }
2539
2540            if (mFirstBoot) {
2541                requestCopyPreoptedFiles();
2542            }
2543
2544            String customResolverActivity = Resources.getSystem().getString(
2545                    R.string.config_customResolverActivity);
2546            if (TextUtils.isEmpty(customResolverActivity)) {
2547                customResolverActivity = null;
2548            } else {
2549                mCustomResolverComponentName = ComponentName.unflattenFromString(
2550                        customResolverActivity);
2551            }
2552
2553            long startTime = SystemClock.uptimeMillis();
2554
2555            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2556                    startTime);
2557
2558            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2559            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2560
2561            if (bootClassPath == null) {
2562                Slog.w(TAG, "No BOOTCLASSPATH found!");
2563            }
2564
2565            if (systemServerClassPath == null) {
2566                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2567            }
2568
2569            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2570
2571            final VersionInfo ver = mSettings.getInternalVersion();
2572            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2573            if (mIsUpgrade) {
2574                logCriticalInfo(Log.INFO,
2575                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2576            }
2577
2578            // when upgrading from pre-M, promote system app permissions from install to runtime
2579            mPromoteSystemApps =
2580                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2581
2582            // When upgrading from pre-N, we need to handle package extraction like first boot,
2583            // as there is no profiling data available.
2584            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2585
2586            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2587
2588            // save off the names of pre-existing system packages prior to scanning; we don't
2589            // want to automatically grant runtime permissions for new system apps
2590            if (mPromoteSystemApps) {
2591                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2592                while (pkgSettingIter.hasNext()) {
2593                    PackageSetting ps = pkgSettingIter.next();
2594                    if (isSystemApp(ps)) {
2595                        mExistingSystemPackages.add(ps.name);
2596                    }
2597                }
2598            }
2599
2600            mCacheDir = preparePackageParserCache(mIsUpgrade);
2601
2602            // Set flag to monitor and not change apk file paths when
2603            // scanning install directories.
2604            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2605
2606            if (mIsUpgrade || mFirstBoot) {
2607                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2608            }
2609
2610            // Collect vendor overlay packages. (Do this before scanning any apps.)
2611            // For security and version matching reason, only consider
2612            // overlay packages if they reside in the right directory.
2613            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2614                    | PackageParser.PARSE_IS_SYSTEM
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR
2616                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2617
2618            mParallelPackageParserCallback.findStaticOverlayPackages();
2619
2620            // Find base frameworks (resource packages without code).
2621            scanDirTracedLI(frameworkDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR
2624                    | PackageParser.PARSE_IS_PRIVILEGED,
2625                    scanFlags | SCAN_NO_DEX, 0);
2626
2627            // Collected privileged system packages.
2628            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2629            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2630                    | PackageParser.PARSE_IS_SYSTEM
2631                    | PackageParser.PARSE_IS_SYSTEM_DIR
2632                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2633
2634            // Collect ordinary system packages.
2635            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2636            scanDirTracedLI(systemAppDir, mDefParseFlags
2637                    | PackageParser.PARSE_IS_SYSTEM
2638                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2639
2640            // Collect all vendor packages.
2641            File vendorAppDir = new File("/vendor/app");
2642            try {
2643                vendorAppDir = vendorAppDir.getCanonicalFile();
2644            } catch (IOException e) {
2645                // failed to look up canonical path, continue with original one
2646            }
2647            scanDirTracedLI(vendorAppDir, mDefParseFlags
2648                    | PackageParser.PARSE_IS_SYSTEM
2649                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2650
2651            // Collect all OEM packages.
2652            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2653            scanDirTracedLI(oemAppDir, mDefParseFlags
2654                    | PackageParser.PARSE_IS_SYSTEM
2655                    | PackageParser.PARSE_IS_SYSTEM_DIR
2656                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2657
2658            // Prune any system packages that no longer exist.
2659            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2660            // Stub packages must either be replaced with full versions in the /data
2661            // partition or be disabled.
2662            final List<String> stubSystemApps = new ArrayList<>();
2663            if (!mOnlyCore) {
2664                // do this first before mucking with mPackages for the "expecting better" case
2665                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2666                while (pkgIterator.hasNext()) {
2667                    final PackageParser.Package pkg = pkgIterator.next();
2668                    if (pkg.isStub) {
2669                        stubSystemApps.add(pkg.packageName);
2670                    }
2671                }
2672
2673                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2674                while (psit.hasNext()) {
2675                    PackageSetting ps = psit.next();
2676
2677                    /*
2678                     * If this is not a system app, it can't be a
2679                     * disable system app.
2680                     */
2681                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2682                        continue;
2683                    }
2684
2685                    /*
2686                     * If the package is scanned, it's not erased.
2687                     */
2688                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2689                    if (scannedPkg != null) {
2690                        /*
2691                         * If the system app is both scanned and in the
2692                         * disabled packages list, then it must have been
2693                         * added via OTA. Remove it from the currently
2694                         * scanned package so the previously user-installed
2695                         * application can be scanned.
2696                         */
2697                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2698                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2699                                    + ps.name + "; removing system app.  Last known codePath="
2700                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2701                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2702                                    + scannedPkg.mVersionCode);
2703                            removePackageLI(scannedPkg, true);
2704                            mExpectingBetter.put(ps.name, ps.codePath);
2705                        }
2706
2707                        continue;
2708                    }
2709
2710                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2711                        psit.remove();
2712                        logCriticalInfo(Log.WARN, "System package " + ps.name
2713                                + " no longer exists; it's data will be wiped");
2714                        // Actual deletion of code and data will be handled by later
2715                        // reconciliation step
2716                    } else {
2717                        // we still have a disabled system package, but, it still might have
2718                        // been removed. check the code path still exists and check there's
2719                        // still a package. the latter can happen if an OTA keeps the same
2720                        // code path, but, changes the package name.
2721                        final PackageSetting disabledPs =
2722                                mSettings.getDisabledSystemPkgLPr(ps.name);
2723                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2724                                || disabledPs.pkg == null) {
2725                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2726                        }
2727                    }
2728                }
2729            }
2730
2731            //look for any incomplete package installations
2732            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2733            for (int i = 0; i < deletePkgsList.size(); i++) {
2734                // Actual deletion of code and data will be handled by later
2735                // reconciliation step
2736                final String packageName = deletePkgsList.get(i).name;
2737                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2738                synchronized (mPackages) {
2739                    mSettings.removePackageLPw(packageName);
2740                }
2741            }
2742
2743            //delete tmp files
2744            deleteTempPackageFiles();
2745
2746            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2747
2748            // Remove any shared userIDs that have no associated packages
2749            mSettings.pruneSharedUsersLPw();
2750            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2751            final int systemPackagesCount = mPackages.size();
2752            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2753                    + " ms, packageCount: " + systemPackagesCount
2754                    + " , timePerPackage: "
2755                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2756                    + " , cached: " + cachedSystemApps);
2757            if (mIsUpgrade && systemPackagesCount > 0) {
2758                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2759                        ((int) systemScanTime) / systemPackagesCount);
2760            }
2761            if (!mOnlyCore) {
2762                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2763                        SystemClock.uptimeMillis());
2764                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2765
2766                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2767                        | PackageParser.PARSE_FORWARD_LOCK,
2768                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2769
2770                // Remove disable package settings for updated system apps that were
2771                // removed via an OTA. If the update is no longer present, remove the
2772                // app completely. Otherwise, revoke their system privileges.
2773                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2774                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2775                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2776
2777                    final String msg;
2778                    if (deletedPkg == null) {
2779                        // should have found an update, but, we didn't; remove everything
2780                        msg = "Updated system package " + deletedAppName
2781                                + " no longer exists; removing its data";
2782                        // Actual deletion of code and data will be handled by later
2783                        // reconciliation step
2784                    } else {
2785                        // found an update; revoke system privileges
2786                        msg = "Updated system package + " + deletedAppName
2787                                + " no longer exists; revoking system privileges";
2788
2789                        // Don't do anything if a stub is removed from the system image. If
2790                        // we were to remove the uncompressed version from the /data partition,
2791                        // this is where it'd be done.
2792
2793                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2794                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2795                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2796                    }
2797                    logCriticalInfo(Log.WARN, msg);
2798                }
2799
2800                /*
2801                 * Make sure all system apps that we expected to appear on
2802                 * the userdata partition actually showed up. If they never
2803                 * appeared, crawl back and revive the system version.
2804                 */
2805                for (int i = 0; i < mExpectingBetter.size(); i++) {
2806                    final String packageName = mExpectingBetter.keyAt(i);
2807                    if (!mPackages.containsKey(packageName)) {
2808                        final File scanFile = mExpectingBetter.valueAt(i);
2809
2810                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2811                                + " but never showed up; reverting to system");
2812
2813                        int reparseFlags = mDefParseFlags;
2814                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2815                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2816                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2817                                    | PackageParser.PARSE_IS_PRIVILEGED;
2818                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2819                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2820                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2821                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2822                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2823                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2824                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2825                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2826                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2827                                    | PackageParser.PARSE_IS_OEM;
2828                        } else {
2829                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2830                            continue;
2831                        }
2832
2833                        mSettings.enableSystemPackageLPw(packageName);
2834
2835                        try {
2836                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2837                        } catch (PackageManagerException e) {
2838                            Slog.e(TAG, "Failed to parse original system package: "
2839                                    + e.getMessage());
2840                        }
2841                    }
2842                }
2843
2844                // Uncompress and install any stubbed system applications.
2845                // This must be done last to ensure all stubs are replaced or disabled.
2846                decompressSystemApplications(stubSystemApps, scanFlags);
2847
2848                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2849                                - cachedSystemApps;
2850
2851                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2852                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2853                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2854                        + " ms, packageCount: " + dataPackagesCount
2855                        + " , timePerPackage: "
2856                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2857                        + " , cached: " + cachedNonSystemApps);
2858                if (mIsUpgrade && dataPackagesCount > 0) {
2859                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2860                            ((int) dataScanTime) / dataPackagesCount);
2861                }
2862            }
2863            mExpectingBetter.clear();
2864
2865            // Resolve the storage manager.
2866            mStorageManagerPackage = getStorageManagerPackageName();
2867
2868            // Resolve protected action filters. Only the setup wizard is allowed to
2869            // have a high priority filter for these actions.
2870            mSetupWizardPackage = getSetupWizardPackageName();
2871            if (mProtectedFilters.size() > 0) {
2872                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2873                    Slog.i(TAG, "No setup wizard;"
2874                        + " All protected intents capped to priority 0");
2875                }
2876                for (ActivityIntentInfo filter : mProtectedFilters) {
2877                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2878                        if (DEBUG_FILTERS) {
2879                            Slog.i(TAG, "Found setup wizard;"
2880                                + " allow priority " + filter.getPriority() + ";"
2881                                + " package: " + filter.activity.info.packageName
2882                                + " activity: " + filter.activity.className
2883                                + " priority: " + filter.getPriority());
2884                        }
2885                        // skip setup wizard; allow it to keep the high priority filter
2886                        continue;
2887                    }
2888                    if (DEBUG_FILTERS) {
2889                        Slog.i(TAG, "Protected action; cap priority to 0;"
2890                                + " package: " + filter.activity.info.packageName
2891                                + " activity: " + filter.activity.className
2892                                + " origPrio: " + filter.getPriority());
2893                    }
2894                    filter.setPriority(0);
2895                }
2896            }
2897            mDeferProtectedFilters = false;
2898            mProtectedFilters.clear();
2899
2900            // Now that we know all of the shared libraries, update all clients to have
2901            // the correct library paths.
2902            updateAllSharedLibrariesLPw(null);
2903
2904            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2905                // NOTE: We ignore potential failures here during a system scan (like
2906                // the rest of the commands above) because there's precious little we
2907                // can do about it. A settings error is reported, though.
2908                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2909            }
2910
2911            // Now that we know all the packages we are keeping,
2912            // read and update their last usage times.
2913            mPackageUsage.read(mPackages);
2914            mCompilerStats.read();
2915
2916            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2917                    SystemClock.uptimeMillis());
2918            Slog.i(TAG, "Time to scan packages: "
2919                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2920                    + " seconds");
2921
2922            // If the platform SDK has changed since the last time we booted,
2923            // we need to re-grant app permission to catch any new ones that
2924            // appear.  This is really a hack, and means that apps can in some
2925            // cases get permissions that the user didn't initially explicitly
2926            // allow...  it would be nice to have some better way to handle
2927            // this situation.
2928            int updateFlags = UPDATE_PERMISSIONS_ALL;
2929            if (ver.sdkVersion != mSdkVersion) {
2930                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2931                        + mSdkVersion + "; regranting permissions for internal storage");
2932                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2933            }
2934            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2935            ver.sdkVersion = mSdkVersion;
2936
2937            // If this is the first boot or an update from pre-M, and it is a normal
2938            // boot, then we need to initialize the default preferred apps across
2939            // all defined users.
2940            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2941                for (UserInfo user : sUserManager.getUsers(true)) {
2942                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2943                    applyFactoryDefaultBrowserLPw(user.id);
2944                    primeDomainVerificationsLPw(user.id);
2945                }
2946            }
2947
2948            // Prepare storage for system user really early during boot,
2949            // since core system apps like SettingsProvider and SystemUI
2950            // can't wait for user to start
2951            final int storageFlags;
2952            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2953                storageFlags = StorageManager.FLAG_STORAGE_DE;
2954            } else {
2955                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2956            }
2957            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2958                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2959                    true /* onlyCoreApps */);
2960            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2961                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2962                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2963                traceLog.traceBegin("AppDataFixup");
2964                try {
2965                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2966                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2967                } catch (InstallerException e) {
2968                    Slog.w(TAG, "Trouble fixing GIDs", e);
2969                }
2970                traceLog.traceEnd();
2971
2972                traceLog.traceBegin("AppDataPrepare");
2973                if (deferPackages == null || deferPackages.isEmpty()) {
2974                    return;
2975                }
2976                int count = 0;
2977                for (String pkgName : deferPackages) {
2978                    PackageParser.Package pkg = null;
2979                    synchronized (mPackages) {
2980                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2981                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2982                            pkg = ps.pkg;
2983                        }
2984                    }
2985                    if (pkg != null) {
2986                        synchronized (mInstallLock) {
2987                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2988                                    true /* maybeMigrateAppData */);
2989                        }
2990                        count++;
2991                    }
2992                }
2993                traceLog.traceEnd();
2994                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2995            }, "prepareAppData");
2996
2997            // If this is first boot after an OTA, and a normal boot, then
2998            // we need to clear code cache directories.
2999            // Note that we do *not* clear the application profiles. These remain valid
3000            // across OTAs and are used to drive profile verification (post OTA) and
3001            // profile compilation (without waiting to collect a fresh set of profiles).
3002            if (mIsUpgrade && !onlyCore) {
3003                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3004                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3005                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3006                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3007                        // No apps are running this early, so no need to freeze
3008                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3009                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3010                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3011                    }
3012                }
3013                ver.fingerprint = Build.FINGERPRINT;
3014            }
3015
3016            checkDefaultBrowser();
3017
3018            // clear only after permissions and other defaults have been updated
3019            mExistingSystemPackages.clear();
3020            mPromoteSystemApps = false;
3021
3022            // All the changes are done during package scanning.
3023            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3024
3025            // can downgrade to reader
3026            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3027            mSettings.writeLPr();
3028            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3029            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3030                    SystemClock.uptimeMillis());
3031
3032            if (!mOnlyCore) {
3033                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3034                mRequiredInstallerPackage = getRequiredInstallerLPr();
3035                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3036                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3037                if (mIntentFilterVerifierComponent != null) {
3038                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3039                            mIntentFilterVerifierComponent);
3040                } else {
3041                    mIntentFilterVerifier = null;
3042                }
3043                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3044                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3045                        SharedLibraryInfo.VERSION_UNDEFINED);
3046                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3047                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3048                        SharedLibraryInfo.VERSION_UNDEFINED);
3049            } else {
3050                mRequiredVerifierPackage = null;
3051                mRequiredInstallerPackage = null;
3052                mRequiredUninstallerPackage = null;
3053                mIntentFilterVerifierComponent = null;
3054                mIntentFilterVerifier = null;
3055                mServicesSystemSharedLibraryPackageName = null;
3056                mSharedSystemSharedLibraryPackageName = null;
3057            }
3058
3059            mInstallerService = new PackageInstallerService(context, this);
3060            final Pair<ComponentName, String> instantAppResolverComponent =
3061                    getInstantAppResolverLPr();
3062            if (instantAppResolverComponent != null) {
3063                if (DEBUG_EPHEMERAL) {
3064                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3065                }
3066                mInstantAppResolverConnection = new EphemeralResolverConnection(
3067                        mContext, instantAppResolverComponent.first,
3068                        instantAppResolverComponent.second);
3069                mInstantAppResolverSettingsComponent =
3070                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3071            } else {
3072                mInstantAppResolverConnection = null;
3073                mInstantAppResolverSettingsComponent = null;
3074            }
3075            updateInstantAppInstallerLocked(null);
3076
3077            // Read and update the usage of dex files.
3078            // Do this at the end of PM init so that all the packages have their
3079            // data directory reconciled.
3080            // At this point we know the code paths of the packages, so we can validate
3081            // the disk file and build the internal cache.
3082            // The usage file is expected to be small so loading and verifying it
3083            // should take a fairly small time compare to the other activities (e.g. package
3084            // scanning).
3085            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3086            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3087            for (int userId : currentUserIds) {
3088                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3089            }
3090            mDexManager.load(userPackages);
3091            if (mIsUpgrade) {
3092                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3093                        (int) (SystemClock.uptimeMillis() - startTime));
3094            }
3095        } // synchronized (mPackages)
3096        } // synchronized (mInstallLock)
3097
3098        // Now after opening every single application zip, make sure they
3099        // are all flushed.  Not really needed, but keeps things nice and
3100        // tidy.
3101        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3102        Runtime.getRuntime().gc();
3103        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3104
3105        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3106        FallbackCategoryProvider.loadFallbacks();
3107        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3108
3109        // The initial scanning above does many calls into installd while
3110        // holding the mPackages lock, but we're mostly interested in yelling
3111        // once we have a booted system.
3112        mInstaller.setWarnIfHeld(mPackages);
3113
3114        // Expose private service for system components to use.
3115        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3116        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3117    }
3118
3119    /**
3120     * Uncompress and install stub applications.
3121     * <p>In order to save space on the system partition, some applications are shipped in a
3122     * compressed form. In addition the compressed bits for the full application, the
3123     * system image contains a tiny stub comprised of only the Android manifest.
3124     * <p>During the first boot, attempt to uncompress and install the full application. If
3125     * the application can't be installed for any reason, disable the stub and prevent
3126     * uncompressing the full application during future boots.
3127     * <p>In order to forcefully attempt an installation of a full application, go to app
3128     * settings and enable the application.
3129     */
3130    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3131        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3132            final String pkgName = stubSystemApps.get(i);
3133            // skip if the system package is already disabled
3134            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3135                stubSystemApps.remove(i);
3136                continue;
3137            }
3138            // skip if the package isn't installed (?!); this should never happen
3139            final PackageParser.Package pkg = mPackages.get(pkgName);
3140            if (pkg == null) {
3141                stubSystemApps.remove(i);
3142                continue;
3143            }
3144            // skip if the package has been disabled by the user
3145            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3146            if (ps != null) {
3147                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3148                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3149                    stubSystemApps.remove(i);
3150                    continue;
3151                }
3152            }
3153
3154            if (DEBUG_COMPRESSION) {
3155                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3156            }
3157
3158            // uncompress the binary to its eventual destination on /data
3159            final File scanFile = decompressPackage(pkg);
3160            if (scanFile == null) {
3161                continue;
3162            }
3163
3164            // install the package to replace the stub on /system
3165            try {
3166                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3167                removePackageLI(pkg, true /*chatty*/);
3168                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3169                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3170                        UserHandle.USER_SYSTEM, "android");
3171                stubSystemApps.remove(i);
3172                continue;
3173            } catch (PackageManagerException e) {
3174                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3175            }
3176
3177            // any failed attempt to install the package will be cleaned up later
3178        }
3179
3180        // disable any stub still left; these failed to install the full application
3181        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3182            final String pkgName = stubSystemApps.get(i);
3183            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3184            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3185                    UserHandle.USER_SYSTEM, "android");
3186            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3187        }
3188    }
3189
3190    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3191        if (DEBUG_COMPRESSION) {
3192            Slog.i(TAG, "Decompress file"
3193                    + "; src: " + srcFile.getAbsolutePath()
3194                    + ", dst: " + dstFile.getAbsolutePath());
3195        }
3196        try (
3197                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3198                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3199        ) {
3200            Streams.copy(fileIn, fileOut);
3201            Os.chmod(dstFile.getAbsolutePath(), 0644);
3202            return PackageManager.INSTALL_SUCCEEDED;
3203        } catch (IOException e) {
3204            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3205                    + "; src: " + srcFile.getAbsolutePath()
3206                    + ", dst: " + dstFile.getAbsolutePath());
3207        }
3208        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3209    }
3210
3211    private File[] getCompressedFiles(String codePath) {
3212        final File stubCodePath = new File(codePath);
3213        final String stubName = stubCodePath.getName();
3214
3215        // The layout of a compressed package on a given partition is as follows :
3216        //
3217        // Compressed artifacts:
3218        //
3219        // /partition/ModuleName/foo.gz
3220        // /partation/ModuleName/bar.gz
3221        //
3222        // Stub artifact:
3223        //
3224        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3225        //
3226        // In other words, stub is on the same partition as the compressed artifacts
3227        // and in a directory that's suffixed with "-Stub".
3228        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3229        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3230            return null;
3231        }
3232
3233        final File stubParentDir = stubCodePath.getParentFile();
3234        if (stubParentDir == null) {
3235            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3236            return null;
3237        }
3238
3239        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3240        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3241            @Override
3242            public boolean accept(File dir, String name) {
3243                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3244            }
3245        });
3246
3247        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3248            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3249        }
3250
3251        return files;
3252    }
3253
3254    private boolean compressedFileExists(String codePath) {
3255        final File[] compressedFiles = getCompressedFiles(codePath);
3256        return compressedFiles != null && compressedFiles.length > 0;
3257    }
3258
3259    /**
3260     * Decompresses the given package on the system image onto
3261     * the /data partition.
3262     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3263     */
3264    private File decompressPackage(PackageParser.Package pkg) {
3265        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3266        if (compressedFiles == null || compressedFiles.length == 0) {
3267            if (DEBUG_COMPRESSION) {
3268                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3269            }
3270            return null;
3271        }
3272        final File dstCodePath =
3273                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3274        int ret = PackageManager.INSTALL_SUCCEEDED;
3275        try {
3276            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3277            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3278            for (File srcFile : compressedFiles) {
3279                final String srcFileName = srcFile.getName();
3280                final String dstFileName = srcFileName.substring(
3281                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3282                final File dstFile = new File(dstCodePath, dstFileName);
3283                ret = decompressFile(srcFile, dstFile);
3284                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3285                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3286                            + "; pkg: " + pkg.packageName
3287                            + ", file: " + dstFileName);
3288                    break;
3289                }
3290            }
3291        } catch (ErrnoException e) {
3292            logCriticalInfo(Log.ERROR, "Failed to decompress"
3293                    + "; pkg: " + pkg.packageName
3294                    + ", err: " + e.errno);
3295        }
3296        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3297            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3298            NativeLibraryHelper.Handle handle = null;
3299            try {
3300                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3301                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3302                        null /*abiOverride*/);
3303            } catch (IOException e) {
3304                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3305                        + "; pkg: " + pkg.packageName);
3306                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3307            } finally {
3308                IoUtils.closeQuietly(handle);
3309            }
3310        }
3311        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3312            if (dstCodePath == null || !dstCodePath.exists()) {
3313                return null;
3314            }
3315            removeCodePathLI(dstCodePath);
3316            return null;
3317        }
3318        return dstCodePath;
3319    }
3320
3321    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3322        // we're only interested in updating the installer appliction when 1) it's not
3323        // already set or 2) the modified package is the installer
3324        if (mInstantAppInstallerActivity != null
3325                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3326                        .equals(modifiedPackage)) {
3327            return;
3328        }
3329        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3330    }
3331
3332    private static File preparePackageParserCache(boolean isUpgrade) {
3333        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3334            return null;
3335        }
3336
3337        // Disable package parsing on eng builds to allow for faster incremental development.
3338        if (Build.IS_ENG) {
3339            return null;
3340        }
3341
3342        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3343            Slog.i(TAG, "Disabling package parser cache due to system property.");
3344            return null;
3345        }
3346
3347        // The base directory for the package parser cache lives under /data/system/.
3348        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3349                "package_cache");
3350        if (cacheBaseDir == null) {
3351            return null;
3352        }
3353
3354        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3355        // This also serves to "GC" unused entries when the package cache version changes (which
3356        // can only happen during upgrades).
3357        if (isUpgrade) {
3358            FileUtils.deleteContents(cacheBaseDir);
3359        }
3360
3361
3362        // Return the versioned package cache directory. This is something like
3363        // "/data/system/package_cache/1"
3364        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3365
3366        // The following is a workaround to aid development on non-numbered userdebug
3367        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3368        // the system partition is newer.
3369        //
3370        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3371        // that starts with "eng." to signify that this is an engineering build and not
3372        // destined for release.
3373        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3374            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3375
3376            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3377            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3378            // in general and should not be used for production changes. In this specific case,
3379            // we know that they will work.
3380            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3381            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3382                FileUtils.deleteContents(cacheBaseDir);
3383                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3384            }
3385        }
3386
3387        return cacheDir;
3388    }
3389
3390    @Override
3391    public boolean isFirstBoot() {
3392        // allow instant applications
3393        return mFirstBoot;
3394    }
3395
3396    @Override
3397    public boolean isOnlyCoreApps() {
3398        // allow instant applications
3399        return mOnlyCore;
3400    }
3401
3402    @Override
3403    public boolean isUpgrade() {
3404        // allow instant applications
3405        return mIsUpgrade;
3406    }
3407
3408    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3409        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3410
3411        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3412                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3413                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3414        if (matches.size() == 1) {
3415            return matches.get(0).getComponentInfo().packageName;
3416        } else if (matches.size() == 0) {
3417            Log.e(TAG, "There should probably be a verifier, but, none were found");
3418            return null;
3419        }
3420        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3421    }
3422
3423    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3424        synchronized (mPackages) {
3425            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3426            if (libraryEntry == null) {
3427                throw new IllegalStateException("Missing required shared library:" + name);
3428            }
3429            return libraryEntry.apk;
3430        }
3431    }
3432
3433    private @NonNull String getRequiredInstallerLPr() {
3434        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3435        intent.addCategory(Intent.CATEGORY_DEFAULT);
3436        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3437
3438        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3439                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3440                UserHandle.USER_SYSTEM);
3441        if (matches.size() == 1) {
3442            ResolveInfo resolveInfo = matches.get(0);
3443            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3444                throw new RuntimeException("The installer must be a privileged app");
3445            }
3446            return matches.get(0).getComponentInfo().packageName;
3447        } else {
3448            throw new RuntimeException("There must be exactly one installer; found " + matches);
3449        }
3450    }
3451
3452    private @NonNull String getRequiredUninstallerLPr() {
3453        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3454        intent.addCategory(Intent.CATEGORY_DEFAULT);
3455        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3456
3457        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3458                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3459                UserHandle.USER_SYSTEM);
3460        if (resolveInfo == null ||
3461                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3462            throw new RuntimeException("There must be exactly one uninstaller; found "
3463                    + resolveInfo);
3464        }
3465        return resolveInfo.getComponentInfo().packageName;
3466    }
3467
3468    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3469        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3470
3471        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3472                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3473                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3474        ResolveInfo best = null;
3475        final int N = matches.size();
3476        for (int i = 0; i < N; i++) {
3477            final ResolveInfo cur = matches.get(i);
3478            final String packageName = cur.getComponentInfo().packageName;
3479            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3480                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3481                continue;
3482            }
3483
3484            if (best == null || cur.priority > best.priority) {
3485                best = cur;
3486            }
3487        }
3488
3489        if (best != null) {
3490            return best.getComponentInfo().getComponentName();
3491        }
3492        Slog.w(TAG, "Intent filter verifier not found");
3493        return null;
3494    }
3495
3496    @Override
3497    public @Nullable ComponentName getInstantAppResolverComponent() {
3498        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3499            return null;
3500        }
3501        synchronized (mPackages) {
3502            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3503            if (instantAppResolver == null) {
3504                return null;
3505            }
3506            return instantAppResolver.first;
3507        }
3508    }
3509
3510    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3511        final String[] packageArray =
3512                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3513        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3514            if (DEBUG_EPHEMERAL) {
3515                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3516            }
3517            return null;
3518        }
3519
3520        final int callingUid = Binder.getCallingUid();
3521        final int resolveFlags =
3522                MATCH_DIRECT_BOOT_AWARE
3523                | MATCH_DIRECT_BOOT_UNAWARE
3524                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3525        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3526        final Intent resolverIntent = new Intent(actionName);
3527        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3528                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3529        // temporarily look for the old action
3530        if (resolvers.size() == 0) {
3531            if (DEBUG_EPHEMERAL) {
3532                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3533            }
3534            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3535            resolverIntent.setAction(actionName);
3536            resolvers = queryIntentServicesInternal(resolverIntent, null,
3537                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3538        }
3539        final int N = resolvers.size();
3540        if (N == 0) {
3541            if (DEBUG_EPHEMERAL) {
3542                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3543            }
3544            return null;
3545        }
3546
3547        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3548        for (int i = 0; i < N; i++) {
3549            final ResolveInfo info = resolvers.get(i);
3550
3551            if (info.serviceInfo == null) {
3552                continue;
3553            }
3554
3555            final String packageName = info.serviceInfo.packageName;
3556            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3557                if (DEBUG_EPHEMERAL) {
3558                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3559                            + " pkg: " + packageName + ", info:" + info);
3560                }
3561                continue;
3562            }
3563
3564            if (DEBUG_EPHEMERAL) {
3565                Slog.v(TAG, "Ephemeral resolver found;"
3566                        + " pkg: " + packageName + ", info:" + info);
3567            }
3568            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3569        }
3570        if (DEBUG_EPHEMERAL) {
3571            Slog.v(TAG, "Ephemeral resolver NOT found");
3572        }
3573        return null;
3574    }
3575
3576    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3577        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3578        intent.addCategory(Intent.CATEGORY_DEFAULT);
3579        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3580
3581        final int resolveFlags =
3582                MATCH_DIRECT_BOOT_AWARE
3583                | MATCH_DIRECT_BOOT_UNAWARE
3584                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3585        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3586                resolveFlags, UserHandle.USER_SYSTEM);
3587        // temporarily look for the old action
3588        if (matches.isEmpty()) {
3589            if (DEBUG_EPHEMERAL) {
3590                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3591            }
3592            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3593            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3594                    resolveFlags, UserHandle.USER_SYSTEM);
3595        }
3596        Iterator<ResolveInfo> iter = matches.iterator();
3597        while (iter.hasNext()) {
3598            final ResolveInfo rInfo = iter.next();
3599            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3600            if (ps != null) {
3601                final PermissionsState permissionsState = ps.getPermissionsState();
3602                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3603                    continue;
3604                }
3605            }
3606            iter.remove();
3607        }
3608        if (matches.size() == 0) {
3609            return null;
3610        } else if (matches.size() == 1) {
3611            return (ActivityInfo) matches.get(0).getComponentInfo();
3612        } else {
3613            throw new RuntimeException(
3614                    "There must be at most one ephemeral installer; found " + matches);
3615        }
3616    }
3617
3618    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3619            @NonNull ComponentName resolver) {
3620        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3621                .addCategory(Intent.CATEGORY_DEFAULT)
3622                .setPackage(resolver.getPackageName());
3623        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3624        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3625                UserHandle.USER_SYSTEM);
3626        // temporarily look for the old action
3627        if (matches.isEmpty()) {
3628            if (DEBUG_EPHEMERAL) {
3629                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3630            }
3631            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3632            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3633                    UserHandle.USER_SYSTEM);
3634        }
3635        if (matches.isEmpty()) {
3636            return null;
3637        }
3638        return matches.get(0).getComponentInfo().getComponentName();
3639    }
3640
3641    private void primeDomainVerificationsLPw(int userId) {
3642        if (DEBUG_DOMAIN_VERIFICATION) {
3643            Slog.d(TAG, "Priming domain verifications in user " + userId);
3644        }
3645
3646        SystemConfig systemConfig = SystemConfig.getInstance();
3647        ArraySet<String> packages = systemConfig.getLinkedApps();
3648
3649        for (String packageName : packages) {
3650            PackageParser.Package pkg = mPackages.get(packageName);
3651            if (pkg != null) {
3652                if (!pkg.isSystemApp()) {
3653                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3654                    continue;
3655                }
3656
3657                ArraySet<String> domains = null;
3658                for (PackageParser.Activity a : pkg.activities) {
3659                    for (ActivityIntentInfo filter : a.intents) {
3660                        if (hasValidDomains(filter)) {
3661                            if (domains == null) {
3662                                domains = new ArraySet<String>();
3663                            }
3664                            domains.addAll(filter.getHostsList());
3665                        }
3666                    }
3667                }
3668
3669                if (domains != null && domains.size() > 0) {
3670                    if (DEBUG_DOMAIN_VERIFICATION) {
3671                        Slog.v(TAG, "      + " + packageName);
3672                    }
3673                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3674                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3675                    // and then 'always' in the per-user state actually used for intent resolution.
3676                    final IntentFilterVerificationInfo ivi;
3677                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3678                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3679                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3680                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3681                } else {
3682                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3683                            + "' does not handle web links");
3684                }
3685            } else {
3686                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3687            }
3688        }
3689
3690        scheduleWritePackageRestrictionsLocked(userId);
3691        scheduleWriteSettingsLocked();
3692    }
3693
3694    private void applyFactoryDefaultBrowserLPw(int userId) {
3695        // The default browser app's package name is stored in a string resource,
3696        // with a product-specific overlay used for vendor customization.
3697        String browserPkg = mContext.getResources().getString(
3698                com.android.internal.R.string.default_browser);
3699        if (!TextUtils.isEmpty(browserPkg)) {
3700            // non-empty string => required to be a known package
3701            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3702            if (ps == null) {
3703                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3704                browserPkg = null;
3705            } else {
3706                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3707            }
3708        }
3709
3710        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3711        // default.  If there's more than one, just leave everything alone.
3712        if (browserPkg == null) {
3713            calculateDefaultBrowserLPw(userId);
3714        }
3715    }
3716
3717    private void calculateDefaultBrowserLPw(int userId) {
3718        List<String> allBrowsers = resolveAllBrowserApps(userId);
3719        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3720        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3721    }
3722
3723    private List<String> resolveAllBrowserApps(int userId) {
3724        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3725        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3726                PackageManager.MATCH_ALL, userId);
3727
3728        final int count = list.size();
3729        List<String> result = new ArrayList<String>(count);
3730        for (int i=0; i<count; i++) {
3731            ResolveInfo info = list.get(i);
3732            if (info.activityInfo == null
3733                    || !info.handleAllWebDataURI
3734                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3735                    || result.contains(info.activityInfo.packageName)) {
3736                continue;
3737            }
3738            result.add(info.activityInfo.packageName);
3739        }
3740
3741        return result;
3742    }
3743
3744    private boolean packageIsBrowser(String packageName, int userId) {
3745        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3746                PackageManager.MATCH_ALL, userId);
3747        final int N = list.size();
3748        for (int i = 0; i < N; i++) {
3749            ResolveInfo info = list.get(i);
3750            if (packageName.equals(info.activityInfo.packageName)) {
3751                return true;
3752            }
3753        }
3754        return false;
3755    }
3756
3757    private void checkDefaultBrowser() {
3758        final int myUserId = UserHandle.myUserId();
3759        final String packageName = getDefaultBrowserPackageName(myUserId);
3760        if (packageName != null) {
3761            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3762            if (info == null) {
3763                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3764                synchronized (mPackages) {
3765                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3766                }
3767            }
3768        }
3769    }
3770
3771    @Override
3772    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3773            throws RemoteException {
3774        try {
3775            return super.onTransact(code, data, reply, flags);
3776        } catch (RuntimeException e) {
3777            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3778                Slog.wtf(TAG, "Package Manager Crash", e);
3779            }
3780            throw e;
3781        }
3782    }
3783
3784    static int[] appendInts(int[] cur, int[] add) {
3785        if (add == null) return cur;
3786        if (cur == null) return add;
3787        final int N = add.length;
3788        for (int i=0; i<N; i++) {
3789            cur = appendInt(cur, add[i]);
3790        }
3791        return cur;
3792    }
3793
3794    /**
3795     * Returns whether or not a full application can see an instant application.
3796     * <p>
3797     * Currently, there are three cases in which this can occur:
3798     * <ol>
3799     * <li>The calling application is a "special" process. The special
3800     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3801     *     and {@code 0}</li>
3802     * <li>The calling application has the permission
3803     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3804     * <li>The calling application is the default launcher on the
3805     *     system partition.</li>
3806     * </ol>
3807     */
3808    private boolean canViewInstantApps(int callingUid, int userId) {
3809        if (callingUid == Process.SYSTEM_UID
3810                || callingUid == Process.SHELL_UID
3811                || callingUid == Process.ROOT_UID) {
3812            return true;
3813        }
3814        if (mContext.checkCallingOrSelfPermission(
3815                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3816            return true;
3817        }
3818        if (mContext.checkCallingOrSelfPermission(
3819                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3820            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3821            if (homeComponent != null
3822                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3823                return true;
3824            }
3825        }
3826        return false;
3827    }
3828
3829    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3830        if (!sUserManager.exists(userId)) return null;
3831        if (ps == null) {
3832            return null;
3833        }
3834        PackageParser.Package p = ps.pkg;
3835        if (p == null) {
3836            return null;
3837        }
3838        final int callingUid = Binder.getCallingUid();
3839        // Filter out ephemeral app metadata:
3840        //   * The system/shell/root can see metadata for any app
3841        //   * An installed app can see metadata for 1) other installed apps
3842        //     and 2) ephemeral apps that have explicitly interacted with it
3843        //   * Ephemeral apps can only see their own data and exposed installed apps
3844        //   * Holding a signature permission allows seeing instant apps
3845        if (filterAppAccessLPr(ps, callingUid, userId)) {
3846            return null;
3847        }
3848
3849        final PermissionsState permissionsState = ps.getPermissionsState();
3850
3851        // Compute GIDs only if requested
3852        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3853                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3854        // Compute granted permissions only if package has requested permissions
3855        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3856                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3857        final PackageUserState state = ps.readUserState(userId);
3858
3859        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3860                && ps.isSystem()) {
3861            flags |= MATCH_ANY_USER;
3862        }
3863
3864        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3865                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3866
3867        if (packageInfo == null) {
3868            return null;
3869        }
3870
3871        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3872                resolveExternalPackageNameLPr(p);
3873
3874        return packageInfo;
3875    }
3876
3877    @Override
3878    public void checkPackageStartable(String packageName, int userId) {
3879        final int callingUid = Binder.getCallingUid();
3880        if (getInstantAppPackageName(callingUid) != null) {
3881            throw new SecurityException("Instant applications don't have access to this method");
3882        }
3883        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3884        synchronized (mPackages) {
3885            final PackageSetting ps = mSettings.mPackages.get(packageName);
3886            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3887                throw new SecurityException("Package " + packageName + " was not found!");
3888            }
3889
3890            if (!ps.getInstalled(userId)) {
3891                throw new SecurityException(
3892                        "Package " + packageName + " was not installed for user " + userId + "!");
3893            }
3894
3895            if (mSafeMode && !ps.isSystem()) {
3896                throw new SecurityException("Package " + packageName + " not a system app!");
3897            }
3898
3899            if (mFrozenPackages.contains(packageName)) {
3900                throw new SecurityException("Package " + packageName + " is currently frozen!");
3901            }
3902
3903            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3904                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3905            }
3906        }
3907    }
3908
3909    @Override
3910    public boolean isPackageAvailable(String packageName, int userId) {
3911        if (!sUserManager.exists(userId)) return false;
3912        final int callingUid = Binder.getCallingUid();
3913        enforceCrossUserPermission(callingUid, userId,
3914                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3915        synchronized (mPackages) {
3916            PackageParser.Package p = mPackages.get(packageName);
3917            if (p != null) {
3918                final PackageSetting ps = (PackageSetting) p.mExtras;
3919                if (filterAppAccessLPr(ps, callingUid, userId)) {
3920                    return false;
3921                }
3922                if (ps != null) {
3923                    final PackageUserState state = ps.readUserState(userId);
3924                    if (state != null) {
3925                        return PackageParser.isAvailable(state);
3926                    }
3927                }
3928            }
3929        }
3930        return false;
3931    }
3932
3933    @Override
3934    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3935        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3936                flags, Binder.getCallingUid(), userId);
3937    }
3938
3939    @Override
3940    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3941            int flags, int userId) {
3942        return getPackageInfoInternal(versionedPackage.getPackageName(),
3943                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3944    }
3945
3946    /**
3947     * Important: The provided filterCallingUid is used exclusively to filter out packages
3948     * that can be seen based on user state. It's typically the original caller uid prior
3949     * to clearing. Because it can only be provided by trusted code, it's value can be
3950     * trusted and will be used as-is; unlike userId which will be validated by this method.
3951     */
3952    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3953            int flags, int filterCallingUid, int userId) {
3954        if (!sUserManager.exists(userId)) return null;
3955        flags = updateFlagsForPackage(flags, userId, packageName);
3956        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3957                false /* requireFullPermission */, false /* checkShell */, "get package info");
3958
3959        // reader
3960        synchronized (mPackages) {
3961            // Normalize package name to handle renamed packages and static libs
3962            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3963
3964            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3965            if (matchFactoryOnly) {
3966                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3967                if (ps != null) {
3968                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3969                        return null;
3970                    }
3971                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3972                        return null;
3973                    }
3974                    return generatePackageInfo(ps, flags, userId);
3975                }
3976            }
3977
3978            PackageParser.Package p = mPackages.get(packageName);
3979            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3980                return null;
3981            }
3982            if (DEBUG_PACKAGE_INFO)
3983                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3984            if (p != null) {
3985                final PackageSetting ps = (PackageSetting) p.mExtras;
3986                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3987                    return null;
3988                }
3989                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3990                    return null;
3991                }
3992                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3993            }
3994            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3995                final PackageSetting ps = mSettings.mPackages.get(packageName);
3996                if (ps == null) return null;
3997                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3998                    return null;
3999                }
4000                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4001                    return null;
4002                }
4003                return generatePackageInfo(ps, flags, userId);
4004            }
4005        }
4006        return null;
4007    }
4008
4009    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4010        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4011            return true;
4012        }
4013        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4014            return true;
4015        }
4016        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4017            return true;
4018        }
4019        return false;
4020    }
4021
4022    private boolean isComponentVisibleToInstantApp(
4023            @Nullable ComponentName component, @ComponentType int type) {
4024        if (type == TYPE_ACTIVITY) {
4025            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4026            return activity != null
4027                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4028                    : false;
4029        } else if (type == TYPE_RECEIVER) {
4030            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4031            return activity != null
4032                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4033                    : false;
4034        } else if (type == TYPE_SERVICE) {
4035            final PackageParser.Service service = mServices.mServices.get(component);
4036            return service != null
4037                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4038                    : false;
4039        } else if (type == TYPE_PROVIDER) {
4040            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4041            return provider != null
4042                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4043                    : false;
4044        } else if (type == TYPE_UNKNOWN) {
4045            return isComponentVisibleToInstantApp(component);
4046        }
4047        return false;
4048    }
4049
4050    /**
4051     * Returns whether or not access to the application should be filtered.
4052     * <p>
4053     * Access may be limited based upon whether the calling or target applications
4054     * are instant applications.
4055     *
4056     * @see #canAccessInstantApps(int)
4057     */
4058    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4059            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4060        // if we're in an isolated process, get the real calling UID
4061        if (Process.isIsolated(callingUid)) {
4062            callingUid = mIsolatedOwners.get(callingUid);
4063        }
4064        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4065        final boolean callerIsInstantApp = instantAppPkgName != null;
4066        if (ps == null) {
4067            if (callerIsInstantApp) {
4068                // pretend the application exists, but, needs to be filtered
4069                return true;
4070            }
4071            return false;
4072        }
4073        // if the target and caller are the same application, don't filter
4074        if (isCallerSameApp(ps.name, callingUid)) {
4075            return false;
4076        }
4077        if (callerIsInstantApp) {
4078            // request for a specific component; if it hasn't been explicitly exposed, filter
4079            if (component != null) {
4080                return !isComponentVisibleToInstantApp(component, componentType);
4081            }
4082            // request for application; if no components have been explicitly exposed, filter
4083            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4084        }
4085        if (ps.getInstantApp(userId)) {
4086            // caller can see all components of all instant applications, don't filter
4087            if (canViewInstantApps(callingUid, userId)) {
4088                return false;
4089            }
4090            // request for a specific instant application component, filter
4091            if (component != null) {
4092                return true;
4093            }
4094            // request for an instant application; if the caller hasn't been granted access, filter
4095            return !mInstantAppRegistry.isInstantAccessGranted(
4096                    userId, UserHandle.getAppId(callingUid), ps.appId);
4097        }
4098        return false;
4099    }
4100
4101    /**
4102     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4103     */
4104    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4105        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4106    }
4107
4108    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4109            int flags) {
4110        // Callers can access only the libs they depend on, otherwise they need to explicitly
4111        // ask for the shared libraries given the caller is allowed to access all static libs.
4112        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4113            // System/shell/root get to see all static libs
4114            final int appId = UserHandle.getAppId(uid);
4115            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4116                    || appId == Process.ROOT_UID) {
4117                return false;
4118            }
4119        }
4120
4121        // No package means no static lib as it is always on internal storage
4122        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4123            return false;
4124        }
4125
4126        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4127                ps.pkg.staticSharedLibVersion);
4128        if (libEntry == null) {
4129            return false;
4130        }
4131
4132        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4133        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4134        if (uidPackageNames == null) {
4135            return true;
4136        }
4137
4138        for (String uidPackageName : uidPackageNames) {
4139            if (ps.name.equals(uidPackageName)) {
4140                return false;
4141            }
4142            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4143            if (uidPs != null) {
4144                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4145                        libEntry.info.getName());
4146                if (index < 0) {
4147                    continue;
4148                }
4149                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4150                    return false;
4151                }
4152            }
4153        }
4154        return true;
4155    }
4156
4157    @Override
4158    public String[] currentToCanonicalPackageNames(String[] names) {
4159        final int callingUid = Binder.getCallingUid();
4160        if (getInstantAppPackageName(callingUid) != null) {
4161            return names;
4162        }
4163        final String[] out = new String[names.length];
4164        // reader
4165        synchronized (mPackages) {
4166            final int callingUserId = UserHandle.getUserId(callingUid);
4167            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4168            for (int i=names.length-1; i>=0; i--) {
4169                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4170                boolean translateName = false;
4171                if (ps != null && ps.realName != null) {
4172                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4173                    translateName = !targetIsInstantApp
4174                            || canViewInstantApps
4175                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4176                                    UserHandle.getAppId(callingUid), ps.appId);
4177                }
4178                out[i] = translateName ? ps.realName : names[i];
4179            }
4180        }
4181        return out;
4182    }
4183
4184    @Override
4185    public String[] canonicalToCurrentPackageNames(String[] names) {
4186        final int callingUid = Binder.getCallingUid();
4187        if (getInstantAppPackageName(callingUid) != null) {
4188            return names;
4189        }
4190        final String[] out = new String[names.length];
4191        // reader
4192        synchronized (mPackages) {
4193            final int callingUserId = UserHandle.getUserId(callingUid);
4194            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4195            for (int i=names.length-1; i>=0; i--) {
4196                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4197                boolean translateName = false;
4198                if (cur != null) {
4199                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4200                    final boolean targetIsInstantApp =
4201                            ps != null && ps.getInstantApp(callingUserId);
4202                    translateName = !targetIsInstantApp
4203                            || canViewInstantApps
4204                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4205                                    UserHandle.getAppId(callingUid), ps.appId);
4206                }
4207                out[i] = translateName ? cur : names[i];
4208            }
4209        }
4210        return out;
4211    }
4212
4213    @Override
4214    public int getPackageUid(String packageName, int flags, int userId) {
4215        if (!sUserManager.exists(userId)) return -1;
4216        final int callingUid = Binder.getCallingUid();
4217        flags = updateFlagsForPackage(flags, userId, packageName);
4218        enforceCrossUserPermission(callingUid, userId,
4219                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4220
4221        // reader
4222        synchronized (mPackages) {
4223            final PackageParser.Package p = mPackages.get(packageName);
4224            if (p != null && p.isMatch(flags)) {
4225                PackageSetting ps = (PackageSetting) p.mExtras;
4226                if (filterAppAccessLPr(ps, callingUid, userId)) {
4227                    return -1;
4228                }
4229                return UserHandle.getUid(userId, p.applicationInfo.uid);
4230            }
4231            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4232                final PackageSetting ps = mSettings.mPackages.get(packageName);
4233                if (ps != null && ps.isMatch(flags)
4234                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4235                    return UserHandle.getUid(userId, ps.appId);
4236                }
4237            }
4238        }
4239
4240        return -1;
4241    }
4242
4243    @Override
4244    public int[] getPackageGids(String packageName, int flags, int userId) {
4245        if (!sUserManager.exists(userId)) return null;
4246        final int callingUid = Binder.getCallingUid();
4247        flags = updateFlagsForPackage(flags, userId, packageName);
4248        enforceCrossUserPermission(callingUid, userId,
4249                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4250
4251        // reader
4252        synchronized (mPackages) {
4253            final PackageParser.Package p = mPackages.get(packageName);
4254            if (p != null && p.isMatch(flags)) {
4255                PackageSetting ps = (PackageSetting) p.mExtras;
4256                if (filterAppAccessLPr(ps, callingUid, userId)) {
4257                    return null;
4258                }
4259                // TODO: Shouldn't this be checking for package installed state for userId and
4260                // return null?
4261                return ps.getPermissionsState().computeGids(userId);
4262            }
4263            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4264                final PackageSetting ps = mSettings.mPackages.get(packageName);
4265                if (ps != null && ps.isMatch(flags)
4266                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4267                    return ps.getPermissionsState().computeGids(userId);
4268                }
4269            }
4270        }
4271
4272        return null;
4273    }
4274
4275    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4276        if (bp.perm != null) {
4277            return PackageParser.generatePermissionInfo(bp.perm, flags);
4278        }
4279        PermissionInfo pi = new PermissionInfo();
4280        pi.name = bp.name;
4281        pi.packageName = bp.sourcePackage;
4282        pi.nonLocalizedLabel = bp.name;
4283        pi.protectionLevel = bp.protectionLevel;
4284        return pi;
4285    }
4286
4287    @Override
4288    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4289        final int callingUid = Binder.getCallingUid();
4290        if (getInstantAppPackageName(callingUid) != null) {
4291            return null;
4292        }
4293        // reader
4294        synchronized (mPackages) {
4295            final BasePermission p = mSettings.mPermissions.get(name);
4296            if (p == null) {
4297                return null;
4298            }
4299            // If the caller is an app that targets pre 26 SDK drop protection flags.
4300            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4301            if (permissionInfo != null) {
4302                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4303                        permissionInfo.protectionLevel, packageName, callingUid);
4304                if (permissionInfo.protectionLevel != protectionLevel) {
4305                    // If we return different protection level, don't use the cached info
4306                    if (p.perm != null && p.perm.info == permissionInfo) {
4307                        permissionInfo = new PermissionInfo(permissionInfo);
4308                    }
4309                    permissionInfo.protectionLevel = protectionLevel;
4310                }
4311            }
4312            return permissionInfo;
4313        }
4314    }
4315
4316    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4317            String packageName, int uid) {
4318        // Signature permission flags area always reported
4319        final int protectionLevelMasked = protectionLevel
4320                & (PermissionInfo.PROTECTION_NORMAL
4321                | PermissionInfo.PROTECTION_DANGEROUS
4322                | PermissionInfo.PROTECTION_SIGNATURE);
4323        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4324            return protectionLevel;
4325        }
4326
4327        // System sees all flags.
4328        final int appId = UserHandle.getAppId(uid);
4329        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4330                || appId == Process.SHELL_UID) {
4331            return protectionLevel;
4332        }
4333
4334        // Normalize package name to handle renamed packages and static libs
4335        packageName = resolveInternalPackageNameLPr(packageName,
4336                PackageManager.VERSION_CODE_HIGHEST);
4337
4338        // Apps that target O see flags for all protection levels.
4339        final PackageSetting ps = mSettings.mPackages.get(packageName);
4340        if (ps == null) {
4341            return protectionLevel;
4342        }
4343        if (ps.appId != appId) {
4344            return protectionLevel;
4345        }
4346
4347        final PackageParser.Package pkg = mPackages.get(packageName);
4348        if (pkg == null) {
4349            return protectionLevel;
4350        }
4351        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4352            return protectionLevelMasked;
4353        }
4354
4355        return protectionLevel;
4356    }
4357
4358    @Override
4359    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4360            int flags) {
4361        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4362            return null;
4363        }
4364        // reader
4365        synchronized (mPackages) {
4366            if (group != null && !mPermissionGroups.containsKey(group)) {
4367                // This is thrown as NameNotFoundException
4368                return null;
4369            }
4370
4371            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4372            for (BasePermission p : mSettings.mPermissions.values()) {
4373                if (group == null) {
4374                    if (p.perm == null || p.perm.info.group == null) {
4375                        out.add(generatePermissionInfo(p, flags));
4376                    }
4377                } else {
4378                    if (p.perm != null && group.equals(p.perm.info.group)) {
4379                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4380                    }
4381                }
4382            }
4383            return new ParceledListSlice<>(out);
4384        }
4385    }
4386
4387    @Override
4388    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4389        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4390            return null;
4391        }
4392        // reader
4393        synchronized (mPackages) {
4394            return PackageParser.generatePermissionGroupInfo(
4395                    mPermissionGroups.get(name), flags);
4396        }
4397    }
4398
4399    @Override
4400    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4401        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4402            return ParceledListSlice.emptyList();
4403        }
4404        // reader
4405        synchronized (mPackages) {
4406            final int N = mPermissionGroups.size();
4407            ArrayList<PermissionGroupInfo> out
4408                    = new ArrayList<PermissionGroupInfo>(N);
4409            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4410                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4411            }
4412            return new ParceledListSlice<>(out);
4413        }
4414    }
4415
4416    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4417            int filterCallingUid, int userId) {
4418        if (!sUserManager.exists(userId)) return null;
4419        PackageSetting ps = mSettings.mPackages.get(packageName);
4420        if (ps != null) {
4421            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4422                return null;
4423            }
4424            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4425                return null;
4426            }
4427            if (ps.pkg == null) {
4428                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4429                if (pInfo != null) {
4430                    return pInfo.applicationInfo;
4431                }
4432                return null;
4433            }
4434            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4435                    ps.readUserState(userId), userId);
4436            if (ai != null) {
4437                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4438            }
4439            return ai;
4440        }
4441        return null;
4442    }
4443
4444    @Override
4445    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4446        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4447    }
4448
4449    /**
4450     * Important: The provided filterCallingUid is used exclusively to filter out applications
4451     * that can be seen based on user state. It's typically the original caller uid prior
4452     * to clearing. Because it can only be provided by trusted code, it's value can be
4453     * trusted and will be used as-is; unlike userId which will be validated by this method.
4454     */
4455    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4456            int filterCallingUid, int userId) {
4457        if (!sUserManager.exists(userId)) return null;
4458        flags = updateFlagsForApplication(flags, userId, packageName);
4459        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4460                false /* requireFullPermission */, false /* checkShell */, "get application info");
4461
4462        // writer
4463        synchronized (mPackages) {
4464            // Normalize package name to handle renamed packages and static libs
4465            packageName = resolveInternalPackageNameLPr(packageName,
4466                    PackageManager.VERSION_CODE_HIGHEST);
4467
4468            PackageParser.Package p = mPackages.get(packageName);
4469            if (DEBUG_PACKAGE_INFO) Log.v(
4470                    TAG, "getApplicationInfo " + packageName
4471                    + ": " + p);
4472            if (p != null) {
4473                PackageSetting ps = mSettings.mPackages.get(packageName);
4474                if (ps == null) return null;
4475                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4476                    return null;
4477                }
4478                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4479                    return null;
4480                }
4481                // Note: isEnabledLP() does not apply here - always return info
4482                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4483                        p, flags, ps.readUserState(userId), userId);
4484                if (ai != null) {
4485                    ai.packageName = resolveExternalPackageNameLPr(p);
4486                }
4487                return ai;
4488            }
4489            if ("android".equals(packageName)||"system".equals(packageName)) {
4490                return mAndroidApplication;
4491            }
4492            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4493                // Already generates the external package name
4494                return generateApplicationInfoFromSettingsLPw(packageName,
4495                        flags, filterCallingUid, userId);
4496            }
4497        }
4498        return null;
4499    }
4500
4501    private String normalizePackageNameLPr(String packageName) {
4502        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4503        return normalizedPackageName != null ? normalizedPackageName : packageName;
4504    }
4505
4506    @Override
4507    public void deletePreloadsFileCache() {
4508        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4509            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4510        }
4511        File dir = Environment.getDataPreloadsFileCacheDirectory();
4512        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4513        FileUtils.deleteContents(dir);
4514    }
4515
4516    @Override
4517    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4518            final int storageFlags, final IPackageDataObserver observer) {
4519        mContext.enforceCallingOrSelfPermission(
4520                android.Manifest.permission.CLEAR_APP_CACHE, null);
4521        mHandler.post(() -> {
4522            boolean success = false;
4523            try {
4524                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4525                success = true;
4526            } catch (IOException e) {
4527                Slog.w(TAG, e);
4528            }
4529            if (observer != null) {
4530                try {
4531                    observer.onRemoveCompleted(null, success);
4532                } catch (RemoteException e) {
4533                    Slog.w(TAG, e);
4534                }
4535            }
4536        });
4537    }
4538
4539    @Override
4540    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4541            final int storageFlags, final IntentSender pi) {
4542        mContext.enforceCallingOrSelfPermission(
4543                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4544        mHandler.post(() -> {
4545            boolean success = false;
4546            try {
4547                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4548                success = true;
4549            } catch (IOException e) {
4550                Slog.w(TAG, e);
4551            }
4552            if (pi != null) {
4553                try {
4554                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4555                } catch (SendIntentException e) {
4556                    Slog.w(TAG, e);
4557                }
4558            }
4559        });
4560    }
4561
4562    /**
4563     * Blocking call to clear various types of cached data across the system
4564     * until the requested bytes are available.
4565     */
4566    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4567        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4568        final File file = storage.findPathForUuid(volumeUuid);
4569        if (file.getUsableSpace() >= bytes) return;
4570
4571        if (ENABLE_FREE_CACHE_V2) {
4572            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4573                    volumeUuid);
4574            final boolean aggressive = (storageFlags
4575                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4576            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4577
4578            // 1. Pre-flight to determine if we have any chance to succeed
4579            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4580            if (internalVolume && (aggressive || SystemProperties
4581                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4582                deletePreloadsFileCache();
4583                if (file.getUsableSpace() >= bytes) return;
4584            }
4585
4586            // 3. Consider parsed APK data (aggressive only)
4587            if (internalVolume && aggressive) {
4588                FileUtils.deleteContents(mCacheDir);
4589                if (file.getUsableSpace() >= bytes) return;
4590            }
4591
4592            // 4. Consider cached app data (above quotas)
4593            try {
4594                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4595                        Installer.FLAG_FREE_CACHE_V2);
4596            } catch (InstallerException ignored) {
4597            }
4598            if (file.getUsableSpace() >= bytes) return;
4599
4600            // 5. Consider shared libraries with refcount=0 and age>min cache period
4601            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4602                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4603                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4604                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4605                return;
4606            }
4607
4608            // 6. Consider dexopt output (aggressive only)
4609            // TODO: Implement
4610
4611            // 7. Consider installed instant apps unused longer than min cache period
4612            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4613                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4614                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4615                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4616                return;
4617            }
4618
4619            // 8. Consider cached app data (below quotas)
4620            try {
4621                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4622                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4623            } catch (InstallerException ignored) {
4624            }
4625            if (file.getUsableSpace() >= bytes) return;
4626
4627            // 9. Consider DropBox entries
4628            // TODO: Implement
4629
4630            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4631            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4632                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4633                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4634                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4635                return;
4636            }
4637        } else {
4638            try {
4639                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4640            } catch (InstallerException ignored) {
4641            }
4642            if (file.getUsableSpace() >= bytes) return;
4643        }
4644
4645        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4646    }
4647
4648    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4649            throws IOException {
4650        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4651        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4652
4653        List<VersionedPackage> packagesToDelete = null;
4654        final long now = System.currentTimeMillis();
4655
4656        synchronized (mPackages) {
4657            final int[] allUsers = sUserManager.getUserIds();
4658            final int libCount = mSharedLibraries.size();
4659            for (int i = 0; i < libCount; i++) {
4660                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4661                if (versionedLib == null) {
4662                    continue;
4663                }
4664                final int versionCount = versionedLib.size();
4665                for (int j = 0; j < versionCount; j++) {
4666                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4667                    // Skip packages that are not static shared libs.
4668                    if (!libInfo.isStatic()) {
4669                        break;
4670                    }
4671                    // Important: We skip static shared libs used for some user since
4672                    // in such a case we need to keep the APK on the device. The check for
4673                    // a lib being used for any user is performed by the uninstall call.
4674                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4675                    // Resolve the package name - we use synthetic package names internally
4676                    final String internalPackageName = resolveInternalPackageNameLPr(
4677                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4678                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4679                    // Skip unused static shared libs cached less than the min period
4680                    // to prevent pruning a lib needed by a subsequently installed package.
4681                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4682                        continue;
4683                    }
4684                    if (packagesToDelete == null) {
4685                        packagesToDelete = new ArrayList<>();
4686                    }
4687                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4688                            declaringPackage.getVersionCode()));
4689                }
4690            }
4691        }
4692
4693        if (packagesToDelete != null) {
4694            final int packageCount = packagesToDelete.size();
4695            for (int i = 0; i < packageCount; i++) {
4696                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4697                // Delete the package synchronously (will fail of the lib used for any user).
4698                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4699                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4700                                == PackageManager.DELETE_SUCCEEDED) {
4701                    if (volume.getUsableSpace() >= neededSpace) {
4702                        return true;
4703                    }
4704                }
4705            }
4706        }
4707
4708        return false;
4709    }
4710
4711    /**
4712     * Update given flags based on encryption status of current user.
4713     */
4714    private int updateFlags(int flags, int userId) {
4715        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4716                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4717            // Caller expressed an explicit opinion about what encryption
4718            // aware/unaware components they want to see, so fall through and
4719            // give them what they want
4720        } else {
4721            // Caller expressed no opinion, so match based on user state
4722            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4723                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4724            } else {
4725                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4726            }
4727        }
4728        return flags;
4729    }
4730
4731    private UserManagerInternal getUserManagerInternal() {
4732        if (mUserManagerInternal == null) {
4733            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4734        }
4735        return mUserManagerInternal;
4736    }
4737
4738    private DeviceIdleController.LocalService getDeviceIdleController() {
4739        if (mDeviceIdleController == null) {
4740            mDeviceIdleController =
4741                    LocalServices.getService(DeviceIdleController.LocalService.class);
4742        }
4743        return mDeviceIdleController;
4744    }
4745
4746    /**
4747     * Update given flags when being used to request {@link PackageInfo}.
4748     */
4749    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4750        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4751        boolean triaged = true;
4752        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4753                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4754            // Caller is asking for component details, so they'd better be
4755            // asking for specific encryption matching behavior, or be triaged
4756            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4757                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4758                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4759                triaged = false;
4760            }
4761        }
4762        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4763                | PackageManager.MATCH_SYSTEM_ONLY
4764                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4765            triaged = false;
4766        }
4767        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4768            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4769                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4770                    + Debug.getCallers(5));
4771        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4772                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4773            // If the caller wants all packages and has a restricted profile associated with it,
4774            // then match all users. This is to make sure that launchers that need to access work
4775            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4776            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4777            flags |= PackageManager.MATCH_ANY_USER;
4778        }
4779        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4780            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4781                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4782        }
4783        return updateFlags(flags, userId);
4784    }
4785
4786    /**
4787     * Update given flags when being used to request {@link ApplicationInfo}.
4788     */
4789    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4790        return updateFlagsForPackage(flags, userId, cookie);
4791    }
4792
4793    /**
4794     * Update given flags when being used to request {@link ComponentInfo}.
4795     */
4796    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4797        if (cookie instanceof Intent) {
4798            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4799                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4800            }
4801        }
4802
4803        boolean triaged = true;
4804        // Caller is asking for component details, so they'd better be
4805        // asking for specific encryption matching behavior, or be triaged
4806        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4807                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4808                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4809            triaged = false;
4810        }
4811        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4812            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4813                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4814        }
4815
4816        return updateFlags(flags, userId);
4817    }
4818
4819    /**
4820     * Update given intent when being used to request {@link ResolveInfo}.
4821     */
4822    private Intent updateIntentForResolve(Intent intent) {
4823        if (intent.getSelector() != null) {
4824            intent = intent.getSelector();
4825        }
4826        if (DEBUG_PREFERRED) {
4827            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4828        }
4829        return intent;
4830    }
4831
4832    /**
4833     * Update given flags when being used to request {@link ResolveInfo}.
4834     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4835     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4836     * flag set. However, this flag is only honoured in three circumstances:
4837     * <ul>
4838     * <li>when called from a system process</li>
4839     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4840     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4841     * action and a {@code android.intent.category.BROWSABLE} category</li>
4842     * </ul>
4843     */
4844    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4845        return updateFlagsForResolve(flags, userId, intent, callingUid,
4846                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4847    }
4848    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4849            boolean wantInstantApps) {
4850        return updateFlagsForResolve(flags, userId, intent, callingUid,
4851                wantInstantApps, false /*onlyExposedExplicitly*/);
4852    }
4853    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4854            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4855        // Safe mode means we shouldn't match any third-party components
4856        if (mSafeMode) {
4857            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4858        }
4859        if (getInstantAppPackageName(callingUid) != null) {
4860            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4861            if (onlyExposedExplicitly) {
4862                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4863            }
4864            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4865            flags |= PackageManager.MATCH_INSTANT;
4866        } else {
4867            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4868            final boolean allowMatchInstant =
4869                    (wantInstantApps
4870                            && Intent.ACTION_VIEW.equals(intent.getAction())
4871                            && hasWebURI(intent))
4872                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4873            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4874                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4875            if (!allowMatchInstant) {
4876                flags &= ~PackageManager.MATCH_INSTANT;
4877            }
4878        }
4879        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4880    }
4881
4882    @Override
4883    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4884        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4885    }
4886
4887    /**
4888     * Important: The provided filterCallingUid is used exclusively to filter out activities
4889     * that can be seen based on user state. It's typically the original caller uid prior
4890     * to clearing. Because it can only be provided by trusted code, it's value can be
4891     * trusted and will be used as-is; unlike userId which will be validated by this method.
4892     */
4893    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4894            int filterCallingUid, int userId) {
4895        if (!sUserManager.exists(userId)) return null;
4896        flags = updateFlagsForComponent(flags, userId, component);
4897        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4898                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4899        synchronized (mPackages) {
4900            PackageParser.Activity a = mActivities.mActivities.get(component);
4901
4902            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4903            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4904                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4905                if (ps == null) return null;
4906                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4907                    return null;
4908                }
4909                return PackageParser.generateActivityInfo(
4910                        a, flags, ps.readUserState(userId), userId);
4911            }
4912            if (mResolveComponentName.equals(component)) {
4913                return PackageParser.generateActivityInfo(
4914                        mResolveActivity, flags, new PackageUserState(), userId);
4915            }
4916        }
4917        return null;
4918    }
4919
4920    @Override
4921    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4922            String resolvedType) {
4923        synchronized (mPackages) {
4924            if (component.equals(mResolveComponentName)) {
4925                // The resolver supports EVERYTHING!
4926                return true;
4927            }
4928            final int callingUid = Binder.getCallingUid();
4929            final int callingUserId = UserHandle.getUserId(callingUid);
4930            PackageParser.Activity a = mActivities.mActivities.get(component);
4931            if (a == null) {
4932                return false;
4933            }
4934            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4935            if (ps == null) {
4936                return false;
4937            }
4938            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4939                return false;
4940            }
4941            for (int i=0; i<a.intents.size(); i++) {
4942                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4943                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4944                    return true;
4945                }
4946            }
4947            return false;
4948        }
4949    }
4950
4951    @Override
4952    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4953        if (!sUserManager.exists(userId)) return null;
4954        final int callingUid = Binder.getCallingUid();
4955        flags = updateFlagsForComponent(flags, userId, component);
4956        enforceCrossUserPermission(callingUid, userId,
4957                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4958        synchronized (mPackages) {
4959            PackageParser.Activity a = mReceivers.mActivities.get(component);
4960            if (DEBUG_PACKAGE_INFO) Log.v(
4961                TAG, "getReceiverInfo " + component + ": " + a);
4962            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4963                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4964                if (ps == null) return null;
4965                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4966                    return null;
4967                }
4968                return PackageParser.generateActivityInfo(
4969                        a, flags, ps.readUserState(userId), userId);
4970            }
4971        }
4972        return null;
4973    }
4974
4975    @Override
4976    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4977            int flags, int userId) {
4978        if (!sUserManager.exists(userId)) return null;
4979        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4980        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4981            return null;
4982        }
4983
4984        flags = updateFlagsForPackage(flags, userId, null);
4985
4986        final boolean canSeeStaticLibraries =
4987                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4988                        == PERMISSION_GRANTED
4989                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4990                        == PERMISSION_GRANTED
4991                || canRequestPackageInstallsInternal(packageName,
4992                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4993                        false  /* throwIfPermNotDeclared*/)
4994                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4995                        == PERMISSION_GRANTED;
4996
4997        synchronized (mPackages) {
4998            List<SharedLibraryInfo> result = null;
4999
5000            final int libCount = mSharedLibraries.size();
5001            for (int i = 0; i < libCount; i++) {
5002                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5003                if (versionedLib == null) {
5004                    continue;
5005                }
5006
5007                final int versionCount = versionedLib.size();
5008                for (int j = 0; j < versionCount; j++) {
5009                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5010                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5011                        break;
5012                    }
5013                    final long identity = Binder.clearCallingIdentity();
5014                    try {
5015                        PackageInfo packageInfo = getPackageInfoVersioned(
5016                                libInfo.getDeclaringPackage(), flags
5017                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5018                        if (packageInfo == null) {
5019                            continue;
5020                        }
5021                    } finally {
5022                        Binder.restoreCallingIdentity(identity);
5023                    }
5024
5025                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5026                            libInfo.getVersion(), libInfo.getType(),
5027                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5028                            flags, userId));
5029
5030                    if (result == null) {
5031                        result = new ArrayList<>();
5032                    }
5033                    result.add(resLibInfo);
5034                }
5035            }
5036
5037            return result != null ? new ParceledListSlice<>(result) : null;
5038        }
5039    }
5040
5041    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5042            SharedLibraryInfo libInfo, int flags, int userId) {
5043        List<VersionedPackage> versionedPackages = null;
5044        final int packageCount = mSettings.mPackages.size();
5045        for (int i = 0; i < packageCount; i++) {
5046            PackageSetting ps = mSettings.mPackages.valueAt(i);
5047
5048            if (ps == null) {
5049                continue;
5050            }
5051
5052            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5053                continue;
5054            }
5055
5056            final String libName = libInfo.getName();
5057            if (libInfo.isStatic()) {
5058                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5059                if (libIdx < 0) {
5060                    continue;
5061                }
5062                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5063                    continue;
5064                }
5065                if (versionedPackages == null) {
5066                    versionedPackages = new ArrayList<>();
5067                }
5068                // If the dependent is a static shared lib, use the public package name
5069                String dependentPackageName = ps.name;
5070                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5071                    dependentPackageName = ps.pkg.manifestPackageName;
5072                }
5073                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5074            } else if (ps.pkg != null) {
5075                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5076                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5077                    if (versionedPackages == null) {
5078                        versionedPackages = new ArrayList<>();
5079                    }
5080                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5081                }
5082            }
5083        }
5084
5085        return versionedPackages;
5086    }
5087
5088    @Override
5089    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5090        if (!sUserManager.exists(userId)) return null;
5091        final int callingUid = Binder.getCallingUid();
5092        flags = updateFlagsForComponent(flags, userId, component);
5093        enforceCrossUserPermission(callingUid, userId,
5094                false /* requireFullPermission */, false /* checkShell */, "get service info");
5095        synchronized (mPackages) {
5096            PackageParser.Service s = mServices.mServices.get(component);
5097            if (DEBUG_PACKAGE_INFO) Log.v(
5098                TAG, "getServiceInfo " + component + ": " + s);
5099            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5100                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5101                if (ps == null) return null;
5102                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5103                    return null;
5104                }
5105                return PackageParser.generateServiceInfo(
5106                        s, flags, ps.readUserState(userId), userId);
5107            }
5108        }
5109        return null;
5110    }
5111
5112    @Override
5113    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5114        if (!sUserManager.exists(userId)) return null;
5115        final int callingUid = Binder.getCallingUid();
5116        flags = updateFlagsForComponent(flags, userId, component);
5117        enforceCrossUserPermission(callingUid, userId,
5118                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5119        synchronized (mPackages) {
5120            PackageParser.Provider p = mProviders.mProviders.get(component);
5121            if (DEBUG_PACKAGE_INFO) Log.v(
5122                TAG, "getProviderInfo " + component + ": " + p);
5123            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5124                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5125                if (ps == null) return null;
5126                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5127                    return null;
5128                }
5129                return PackageParser.generateProviderInfo(
5130                        p, flags, ps.readUserState(userId), userId);
5131            }
5132        }
5133        return null;
5134    }
5135
5136    @Override
5137    public String[] getSystemSharedLibraryNames() {
5138        // allow instant applications
5139        synchronized (mPackages) {
5140            Set<String> libs = null;
5141            final int libCount = mSharedLibraries.size();
5142            for (int i = 0; i < libCount; i++) {
5143                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5144                if (versionedLib == null) {
5145                    continue;
5146                }
5147                final int versionCount = versionedLib.size();
5148                for (int j = 0; j < versionCount; j++) {
5149                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5150                    if (!libEntry.info.isStatic()) {
5151                        if (libs == null) {
5152                            libs = new ArraySet<>();
5153                        }
5154                        libs.add(libEntry.info.getName());
5155                        break;
5156                    }
5157                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5158                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5159                            UserHandle.getUserId(Binder.getCallingUid()),
5160                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5161                        if (libs == null) {
5162                            libs = new ArraySet<>();
5163                        }
5164                        libs.add(libEntry.info.getName());
5165                        break;
5166                    }
5167                }
5168            }
5169
5170            if (libs != null) {
5171                String[] libsArray = new String[libs.size()];
5172                libs.toArray(libsArray);
5173                return libsArray;
5174            }
5175
5176            return null;
5177        }
5178    }
5179
5180    @Override
5181    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5182        // allow instant applications
5183        synchronized (mPackages) {
5184            return mServicesSystemSharedLibraryPackageName;
5185        }
5186    }
5187
5188    @Override
5189    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5190        // allow instant applications
5191        synchronized (mPackages) {
5192            return mSharedSystemSharedLibraryPackageName;
5193        }
5194    }
5195
5196    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5197        for (int i = userList.length - 1; i >= 0; --i) {
5198            final int userId = userList[i];
5199            // don't add instant app to the list of updates
5200            if (pkgSetting.getInstantApp(userId)) {
5201                continue;
5202            }
5203            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5204            if (changedPackages == null) {
5205                changedPackages = new SparseArray<>();
5206                mChangedPackages.put(userId, changedPackages);
5207            }
5208            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5209            if (sequenceNumbers == null) {
5210                sequenceNumbers = new HashMap<>();
5211                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5212            }
5213            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5214            if (sequenceNumber != null) {
5215                changedPackages.remove(sequenceNumber);
5216            }
5217            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5218            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5219        }
5220        mChangedPackagesSequenceNumber++;
5221    }
5222
5223    @Override
5224    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5225        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5226            return null;
5227        }
5228        synchronized (mPackages) {
5229            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5230                return null;
5231            }
5232            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5233            if (changedPackages == null) {
5234                return null;
5235            }
5236            final List<String> packageNames =
5237                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5238            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5239                final String packageName = changedPackages.get(i);
5240                if (packageName != null) {
5241                    packageNames.add(packageName);
5242                }
5243            }
5244            return packageNames.isEmpty()
5245                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5246        }
5247    }
5248
5249    @Override
5250    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5251        // allow instant applications
5252        ArrayList<FeatureInfo> res;
5253        synchronized (mAvailableFeatures) {
5254            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5255            res.addAll(mAvailableFeatures.values());
5256        }
5257        final FeatureInfo fi = new FeatureInfo();
5258        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5259                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5260        res.add(fi);
5261
5262        return new ParceledListSlice<>(res);
5263    }
5264
5265    @Override
5266    public boolean hasSystemFeature(String name, int version) {
5267        // allow instant applications
5268        synchronized (mAvailableFeatures) {
5269            final FeatureInfo feat = mAvailableFeatures.get(name);
5270            if (feat == null) {
5271                return false;
5272            } else {
5273                return feat.version >= version;
5274            }
5275        }
5276    }
5277
5278    @Override
5279    public int checkPermission(String permName, String pkgName, int userId) {
5280        if (!sUserManager.exists(userId)) {
5281            return PackageManager.PERMISSION_DENIED;
5282        }
5283        final int callingUid = Binder.getCallingUid();
5284
5285        synchronized (mPackages) {
5286            final PackageParser.Package p = mPackages.get(pkgName);
5287            if (p != null && p.mExtras != null) {
5288                final PackageSetting ps = (PackageSetting) p.mExtras;
5289                if (filterAppAccessLPr(ps, callingUid, userId)) {
5290                    return PackageManager.PERMISSION_DENIED;
5291                }
5292                final boolean instantApp = ps.getInstantApp(userId);
5293                final PermissionsState permissionsState = ps.getPermissionsState();
5294                if (permissionsState.hasPermission(permName, userId)) {
5295                    if (instantApp) {
5296                        BasePermission bp = mSettings.mPermissions.get(permName);
5297                        if (bp != null && bp.isInstant()) {
5298                            return PackageManager.PERMISSION_GRANTED;
5299                        }
5300                    } else {
5301                        return PackageManager.PERMISSION_GRANTED;
5302                    }
5303                }
5304                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5305                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5306                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5307                    return PackageManager.PERMISSION_GRANTED;
5308                }
5309            }
5310        }
5311
5312        return PackageManager.PERMISSION_DENIED;
5313    }
5314
5315    @Override
5316    public int checkUidPermission(String permName, int uid) {
5317        final int callingUid = Binder.getCallingUid();
5318        final int callingUserId = UserHandle.getUserId(callingUid);
5319        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5320        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5321        final int userId = UserHandle.getUserId(uid);
5322        if (!sUserManager.exists(userId)) {
5323            return PackageManager.PERMISSION_DENIED;
5324        }
5325
5326        synchronized (mPackages) {
5327            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5328            if (obj != null) {
5329                if (obj instanceof SharedUserSetting) {
5330                    if (isCallerInstantApp) {
5331                        return PackageManager.PERMISSION_DENIED;
5332                    }
5333                } else if (obj instanceof PackageSetting) {
5334                    final PackageSetting ps = (PackageSetting) obj;
5335                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5336                        return PackageManager.PERMISSION_DENIED;
5337                    }
5338                }
5339                final SettingBase settingBase = (SettingBase) obj;
5340                final PermissionsState permissionsState = settingBase.getPermissionsState();
5341                if (permissionsState.hasPermission(permName, userId)) {
5342                    if (isUidInstantApp) {
5343                        BasePermission bp = mSettings.mPermissions.get(permName);
5344                        if (bp != null && bp.isInstant()) {
5345                            return PackageManager.PERMISSION_GRANTED;
5346                        }
5347                    } else {
5348                        return PackageManager.PERMISSION_GRANTED;
5349                    }
5350                }
5351                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5352                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5353                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5354                    return PackageManager.PERMISSION_GRANTED;
5355                }
5356            } else {
5357                ArraySet<String> perms = mSystemPermissions.get(uid);
5358                if (perms != null) {
5359                    if (perms.contains(permName)) {
5360                        return PackageManager.PERMISSION_GRANTED;
5361                    }
5362                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5363                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5364                        return PackageManager.PERMISSION_GRANTED;
5365                    }
5366                }
5367            }
5368        }
5369
5370        return PackageManager.PERMISSION_DENIED;
5371    }
5372
5373    @Override
5374    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5375        if (UserHandle.getCallingUserId() != userId) {
5376            mContext.enforceCallingPermission(
5377                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5378                    "isPermissionRevokedByPolicy for user " + userId);
5379        }
5380
5381        if (checkPermission(permission, packageName, userId)
5382                == PackageManager.PERMISSION_GRANTED) {
5383            return false;
5384        }
5385
5386        final int callingUid = Binder.getCallingUid();
5387        if (getInstantAppPackageName(callingUid) != null) {
5388            if (!isCallerSameApp(packageName, callingUid)) {
5389                return false;
5390            }
5391        } else {
5392            if (isInstantApp(packageName, userId)) {
5393                return false;
5394            }
5395        }
5396
5397        final long identity = Binder.clearCallingIdentity();
5398        try {
5399            final int flags = getPermissionFlags(permission, packageName, userId);
5400            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5401        } finally {
5402            Binder.restoreCallingIdentity(identity);
5403        }
5404    }
5405
5406    @Override
5407    public String getPermissionControllerPackageName() {
5408        synchronized (mPackages) {
5409            return mRequiredInstallerPackage;
5410        }
5411    }
5412
5413    /**
5414     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5415     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5416     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5417     * @param message the message to log on security exception
5418     */
5419    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5420            boolean checkShell, String message) {
5421        if (userId < 0) {
5422            throw new IllegalArgumentException("Invalid userId " + userId);
5423        }
5424        if (checkShell) {
5425            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5426        }
5427        if (userId == UserHandle.getUserId(callingUid)) return;
5428        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5429            if (requireFullPermission) {
5430                mContext.enforceCallingOrSelfPermission(
5431                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5432            } else {
5433                try {
5434                    mContext.enforceCallingOrSelfPermission(
5435                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5436                } catch (SecurityException se) {
5437                    mContext.enforceCallingOrSelfPermission(
5438                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5439                }
5440            }
5441        }
5442    }
5443
5444    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5445        if (callingUid == Process.SHELL_UID) {
5446            if (userHandle >= 0
5447                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5448                throw new SecurityException("Shell does not have permission to access user "
5449                        + userHandle);
5450            } else if (userHandle < 0) {
5451                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5452                        + Debug.getCallers(3));
5453            }
5454        }
5455    }
5456
5457    private BasePermission findPermissionTreeLP(String permName) {
5458        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5459            if (permName.startsWith(bp.name) &&
5460                    permName.length() > bp.name.length() &&
5461                    permName.charAt(bp.name.length()) == '.') {
5462                return bp;
5463            }
5464        }
5465        return null;
5466    }
5467
5468    private BasePermission checkPermissionTreeLP(String permName) {
5469        if (permName != null) {
5470            BasePermission bp = findPermissionTreeLP(permName);
5471            if (bp != null) {
5472                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5473                    return bp;
5474                }
5475                throw new SecurityException("Calling uid "
5476                        + Binder.getCallingUid()
5477                        + " is not allowed to add to permission tree "
5478                        + bp.name + " owned by uid " + bp.uid);
5479            }
5480        }
5481        throw new SecurityException("No permission tree found for " + permName);
5482    }
5483
5484    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5485        if (s1 == null) {
5486            return s2 == null;
5487        }
5488        if (s2 == null) {
5489            return false;
5490        }
5491        if (s1.getClass() != s2.getClass()) {
5492            return false;
5493        }
5494        return s1.equals(s2);
5495    }
5496
5497    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5498        if (pi1.icon != pi2.icon) return false;
5499        if (pi1.logo != pi2.logo) return false;
5500        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5501        if (!compareStrings(pi1.name, pi2.name)) return false;
5502        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5503        // We'll take care of setting this one.
5504        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5505        // These are not currently stored in settings.
5506        //if (!compareStrings(pi1.group, pi2.group)) return false;
5507        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5508        //if (pi1.labelRes != pi2.labelRes) return false;
5509        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5510        return true;
5511    }
5512
5513    int permissionInfoFootprint(PermissionInfo info) {
5514        int size = info.name.length();
5515        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5516        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5517        return size;
5518    }
5519
5520    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5521        int size = 0;
5522        for (BasePermission perm : mSettings.mPermissions.values()) {
5523            if (perm.uid == tree.uid) {
5524                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5525            }
5526        }
5527        return size;
5528    }
5529
5530    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5531        // We calculate the max size of permissions defined by this uid and throw
5532        // if that plus the size of 'info' would exceed our stated maximum.
5533        if (tree.uid != Process.SYSTEM_UID) {
5534            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5535            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5536                throw new SecurityException("Permission tree size cap exceeded");
5537            }
5538        }
5539    }
5540
5541    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5542        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5543            throw new SecurityException("Instant apps can't add permissions");
5544        }
5545        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5546            throw new SecurityException("Label must be specified in permission");
5547        }
5548        BasePermission tree = checkPermissionTreeLP(info.name);
5549        BasePermission bp = mSettings.mPermissions.get(info.name);
5550        boolean added = bp == null;
5551        boolean changed = true;
5552        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5553        if (added) {
5554            enforcePermissionCapLocked(info, tree);
5555            bp = new BasePermission(info.name, tree.sourcePackage,
5556                    BasePermission.TYPE_DYNAMIC);
5557        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5558            throw new SecurityException(
5559                    "Not allowed to modify non-dynamic permission "
5560                    + info.name);
5561        } else {
5562            if (bp.protectionLevel == fixedLevel
5563                    && bp.perm.owner.equals(tree.perm.owner)
5564                    && bp.uid == tree.uid
5565                    && comparePermissionInfos(bp.perm.info, info)) {
5566                changed = false;
5567            }
5568        }
5569        bp.protectionLevel = fixedLevel;
5570        info = new PermissionInfo(info);
5571        info.protectionLevel = fixedLevel;
5572        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5573        bp.perm.info.packageName = tree.perm.info.packageName;
5574        bp.uid = tree.uid;
5575        if (added) {
5576            mSettings.mPermissions.put(info.name, bp);
5577        }
5578        if (changed) {
5579            if (!async) {
5580                mSettings.writeLPr();
5581            } else {
5582                scheduleWriteSettingsLocked();
5583            }
5584        }
5585        return added;
5586    }
5587
5588    @Override
5589    public boolean addPermission(PermissionInfo info) {
5590        synchronized (mPackages) {
5591            return addPermissionLocked(info, false);
5592        }
5593    }
5594
5595    @Override
5596    public boolean addPermissionAsync(PermissionInfo info) {
5597        synchronized (mPackages) {
5598            return addPermissionLocked(info, true);
5599        }
5600    }
5601
5602    @Override
5603    public void removePermission(String name) {
5604        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5605            throw new SecurityException("Instant applications don't have access to this method");
5606        }
5607        synchronized (mPackages) {
5608            checkPermissionTreeLP(name);
5609            BasePermission bp = mSettings.mPermissions.get(name);
5610            if (bp != null) {
5611                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5612                    throw new SecurityException(
5613                            "Not allowed to modify non-dynamic permission "
5614                            + name);
5615                }
5616                mSettings.mPermissions.remove(name);
5617                mSettings.writeLPr();
5618            }
5619        }
5620    }
5621
5622    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5623            PackageParser.Package pkg, BasePermission bp) {
5624        int index = pkg.requestedPermissions.indexOf(bp.name);
5625        if (index == -1) {
5626            throw new SecurityException("Package " + pkg.packageName
5627                    + " has not requested permission " + bp.name);
5628        }
5629        if (!bp.isRuntime() && !bp.isDevelopment()) {
5630            throw new SecurityException("Permission " + bp.name
5631                    + " is not a changeable permission type");
5632        }
5633    }
5634
5635    @Override
5636    public void grantRuntimePermission(String packageName, String name, final int userId) {
5637        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5638    }
5639
5640    private void grantRuntimePermission(String packageName, String name, final int userId,
5641            boolean overridePolicy) {
5642        if (!sUserManager.exists(userId)) {
5643            Log.e(TAG, "No such user:" + userId);
5644            return;
5645        }
5646        final int callingUid = Binder.getCallingUid();
5647
5648        mContext.enforceCallingOrSelfPermission(
5649                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5650                "grantRuntimePermission");
5651
5652        enforceCrossUserPermission(callingUid, userId,
5653                true /* requireFullPermission */, true /* checkShell */,
5654                "grantRuntimePermission");
5655
5656        final int uid;
5657        final PackageSetting ps;
5658
5659        synchronized (mPackages) {
5660            final PackageParser.Package pkg = mPackages.get(packageName);
5661            if (pkg == null) {
5662                throw new IllegalArgumentException("Unknown package: " + packageName);
5663            }
5664            final BasePermission bp = mSettings.mPermissions.get(name);
5665            if (bp == null) {
5666                throw new IllegalArgumentException("Unknown permission: " + name);
5667            }
5668            ps = (PackageSetting) pkg.mExtras;
5669            if (ps == null
5670                    || filterAppAccessLPr(ps, callingUid, userId)) {
5671                throw new IllegalArgumentException("Unknown package: " + packageName);
5672            }
5673
5674            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5675
5676            // If a permission review is required for legacy apps we represent
5677            // their permissions as always granted runtime ones since we need
5678            // to keep the review required permission flag per user while an
5679            // install permission's state is shared across all users.
5680            if (mPermissionReviewRequired
5681                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5682                    && bp.isRuntime()) {
5683                return;
5684            }
5685
5686            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5687
5688            final PermissionsState permissionsState = ps.getPermissionsState();
5689
5690            final int flags = permissionsState.getPermissionFlags(name, userId);
5691            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5692                throw new SecurityException("Cannot grant system fixed permission "
5693                        + name + " for package " + packageName);
5694            }
5695            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5696                throw new SecurityException("Cannot grant policy fixed permission "
5697                        + name + " for package " + packageName);
5698            }
5699
5700            if (bp.isDevelopment()) {
5701                // Development permissions must be handled specially, since they are not
5702                // normal runtime permissions.  For now they apply to all users.
5703                if (permissionsState.grantInstallPermission(bp) !=
5704                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5705                    scheduleWriteSettingsLocked();
5706                }
5707                return;
5708            }
5709
5710            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5711                throw new SecurityException("Cannot grant non-ephemeral permission"
5712                        + name + " for package " + packageName);
5713            }
5714
5715            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5716                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5717                return;
5718            }
5719
5720            final int result = permissionsState.grantRuntimePermission(bp, userId);
5721            switch (result) {
5722                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5723                    return;
5724                }
5725
5726                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5727                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5728                    mHandler.post(new Runnable() {
5729                        @Override
5730                        public void run() {
5731                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5732                        }
5733                    });
5734                }
5735                break;
5736            }
5737
5738            if (bp.isRuntime()) {
5739                logPermissionGranted(mContext, name, packageName);
5740            }
5741
5742            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5743
5744            // Not critical if that is lost - app has to request again.
5745            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5746        }
5747
5748        // Only need to do this if user is initialized. Otherwise it's a new user
5749        // and there are no processes running as the user yet and there's no need
5750        // to make an expensive call to remount processes for the changed permissions.
5751        if (READ_EXTERNAL_STORAGE.equals(name)
5752                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5753            final long token = Binder.clearCallingIdentity();
5754            try {
5755                if (sUserManager.isInitialized(userId)) {
5756                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5757                            StorageManagerInternal.class);
5758                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5759                }
5760            } finally {
5761                Binder.restoreCallingIdentity(token);
5762            }
5763        }
5764    }
5765
5766    @Override
5767    public void revokeRuntimePermission(String packageName, String name, int userId) {
5768        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5769    }
5770
5771    private void revokeRuntimePermission(String packageName, String name, int userId,
5772            boolean overridePolicy) {
5773        if (!sUserManager.exists(userId)) {
5774            Log.e(TAG, "No such user:" + userId);
5775            return;
5776        }
5777
5778        mContext.enforceCallingOrSelfPermission(
5779                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5780                "revokeRuntimePermission");
5781
5782        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5783                true /* requireFullPermission */, true /* checkShell */,
5784                "revokeRuntimePermission");
5785
5786        final int appId;
5787
5788        synchronized (mPackages) {
5789            final PackageParser.Package pkg = mPackages.get(packageName);
5790            if (pkg == null) {
5791                throw new IllegalArgumentException("Unknown package: " + packageName);
5792            }
5793            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5794            if (ps == null
5795                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5796                throw new IllegalArgumentException("Unknown package: " + packageName);
5797            }
5798            final BasePermission bp = mSettings.mPermissions.get(name);
5799            if (bp == null) {
5800                throw new IllegalArgumentException("Unknown permission: " + name);
5801            }
5802
5803            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5804
5805            // If a permission review is required for legacy apps we represent
5806            // their permissions as always granted runtime ones since we need
5807            // to keep the review required permission flag per user while an
5808            // install permission's state is shared across all users.
5809            if (mPermissionReviewRequired
5810                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5811                    && bp.isRuntime()) {
5812                return;
5813            }
5814
5815            final PermissionsState permissionsState = ps.getPermissionsState();
5816
5817            final int flags = permissionsState.getPermissionFlags(name, userId);
5818            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5819                throw new SecurityException("Cannot revoke system fixed permission "
5820                        + name + " for package " + packageName);
5821            }
5822            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5823                throw new SecurityException("Cannot revoke policy fixed permission "
5824                        + name + " for package " + packageName);
5825            }
5826
5827            if (bp.isDevelopment()) {
5828                // Development permissions must be handled specially, since they are not
5829                // normal runtime permissions.  For now they apply to all users.
5830                if (permissionsState.revokeInstallPermission(bp) !=
5831                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5832                    scheduleWriteSettingsLocked();
5833                }
5834                return;
5835            }
5836
5837            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5838                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5839                return;
5840            }
5841
5842            if (bp.isRuntime()) {
5843                logPermissionRevoked(mContext, name, packageName);
5844            }
5845
5846            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5847
5848            // Critical, after this call app should never have the permission.
5849            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5850
5851            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5852        }
5853
5854        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5855    }
5856
5857    /**
5858     * Get the first event id for the permission.
5859     *
5860     * <p>There are four events for each permission: <ul>
5861     *     <li>Request permission: first id + 0</li>
5862     *     <li>Grant permission: first id + 1</li>
5863     *     <li>Request for permission denied: first id + 2</li>
5864     *     <li>Revoke permission: first id + 3</li>
5865     * </ul></p>
5866     *
5867     * @param name name of the permission
5868     *
5869     * @return The first event id for the permission
5870     */
5871    private static int getBaseEventId(@NonNull String name) {
5872        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5873
5874        if (eventIdIndex == -1) {
5875            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5876                    || Build.IS_USER) {
5877                Log.i(TAG, "Unknown permission " + name);
5878
5879                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5880            } else {
5881                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5882                //
5883                // Also update
5884                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5885                // - metrics_constants.proto
5886                throw new IllegalStateException("Unknown permission " + name);
5887            }
5888        }
5889
5890        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5891    }
5892
5893    /**
5894     * Log that a permission was revoked.
5895     *
5896     * @param context Context of the caller
5897     * @param name name of the permission
5898     * @param packageName package permission if for
5899     */
5900    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5901            @NonNull String packageName) {
5902        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5903    }
5904
5905    /**
5906     * Log that a permission request was granted.
5907     *
5908     * @param context Context of the caller
5909     * @param name name of the permission
5910     * @param packageName package permission if for
5911     */
5912    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5913            @NonNull String packageName) {
5914        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5915    }
5916
5917    @Override
5918    public void resetRuntimePermissions() {
5919        mContext.enforceCallingOrSelfPermission(
5920                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5921                "revokeRuntimePermission");
5922
5923        int callingUid = Binder.getCallingUid();
5924        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5925            mContext.enforceCallingOrSelfPermission(
5926                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5927                    "resetRuntimePermissions");
5928        }
5929
5930        synchronized (mPackages) {
5931            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5932            for (int userId : UserManagerService.getInstance().getUserIds()) {
5933                final int packageCount = mPackages.size();
5934                for (int i = 0; i < packageCount; i++) {
5935                    PackageParser.Package pkg = mPackages.valueAt(i);
5936                    if (!(pkg.mExtras instanceof PackageSetting)) {
5937                        continue;
5938                    }
5939                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5940                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5941                }
5942            }
5943        }
5944    }
5945
5946    @Override
5947    public int getPermissionFlags(String name, String packageName, int userId) {
5948        if (!sUserManager.exists(userId)) {
5949            return 0;
5950        }
5951
5952        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5953
5954        final int callingUid = Binder.getCallingUid();
5955        enforceCrossUserPermission(callingUid, userId,
5956                true /* requireFullPermission */, false /* checkShell */,
5957                "getPermissionFlags");
5958
5959        synchronized (mPackages) {
5960            final PackageParser.Package pkg = mPackages.get(packageName);
5961            if (pkg == null) {
5962                return 0;
5963            }
5964            final BasePermission bp = mSettings.mPermissions.get(name);
5965            if (bp == null) {
5966                return 0;
5967            }
5968            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5969            if (ps == null
5970                    || filterAppAccessLPr(ps, callingUid, userId)) {
5971                return 0;
5972            }
5973            PermissionsState permissionsState = ps.getPermissionsState();
5974            return permissionsState.getPermissionFlags(name, userId);
5975        }
5976    }
5977
5978    @Override
5979    public void updatePermissionFlags(String name, String packageName, int flagMask,
5980            int flagValues, int userId) {
5981        if (!sUserManager.exists(userId)) {
5982            return;
5983        }
5984
5985        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5986
5987        final int callingUid = Binder.getCallingUid();
5988        enforceCrossUserPermission(callingUid, userId,
5989                true /* requireFullPermission */, true /* checkShell */,
5990                "updatePermissionFlags");
5991
5992        // Only the system can change these flags and nothing else.
5993        if (getCallingUid() != Process.SYSTEM_UID) {
5994            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5995            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5996            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5997            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5998            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5999        }
6000
6001        synchronized (mPackages) {
6002            final PackageParser.Package pkg = mPackages.get(packageName);
6003            if (pkg == null) {
6004                throw new IllegalArgumentException("Unknown package: " + packageName);
6005            }
6006            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6007            if (ps == null
6008                    || filterAppAccessLPr(ps, callingUid, userId)) {
6009                throw new IllegalArgumentException("Unknown package: " + packageName);
6010            }
6011
6012            final BasePermission bp = mSettings.mPermissions.get(name);
6013            if (bp == null) {
6014                throw new IllegalArgumentException("Unknown permission: " + name);
6015            }
6016
6017            PermissionsState permissionsState = ps.getPermissionsState();
6018
6019            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6020
6021            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6022                // Install and runtime permissions are stored in different places,
6023                // so figure out what permission changed and persist the change.
6024                if (permissionsState.getInstallPermissionState(name) != null) {
6025                    scheduleWriteSettingsLocked();
6026                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6027                        || hadState) {
6028                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6029                }
6030            }
6031        }
6032    }
6033
6034    /**
6035     * Update the permission flags for all packages and runtime permissions of a user in order
6036     * to allow device or profile owner to remove POLICY_FIXED.
6037     */
6038    @Override
6039    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6040        if (!sUserManager.exists(userId)) {
6041            return;
6042        }
6043
6044        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6045
6046        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6047                true /* requireFullPermission */, true /* checkShell */,
6048                "updatePermissionFlagsForAllApps");
6049
6050        // Only the system can change system fixed flags.
6051        if (getCallingUid() != Process.SYSTEM_UID) {
6052            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6053            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6054        }
6055
6056        synchronized (mPackages) {
6057            boolean changed = false;
6058            final int packageCount = mPackages.size();
6059            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6060                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6061                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6062                if (ps == null) {
6063                    continue;
6064                }
6065                PermissionsState permissionsState = ps.getPermissionsState();
6066                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6067                        userId, flagMask, flagValues);
6068            }
6069            if (changed) {
6070                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6071            }
6072        }
6073    }
6074
6075    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6076        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6077                != PackageManager.PERMISSION_GRANTED
6078            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6079                != PackageManager.PERMISSION_GRANTED) {
6080            throw new SecurityException(message + " requires "
6081                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6082                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6083        }
6084    }
6085
6086    @Override
6087    public boolean shouldShowRequestPermissionRationale(String permissionName,
6088            String packageName, int userId) {
6089        if (UserHandle.getCallingUserId() != userId) {
6090            mContext.enforceCallingPermission(
6091                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6092                    "canShowRequestPermissionRationale for user " + userId);
6093        }
6094
6095        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6096        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6097            return false;
6098        }
6099
6100        if (checkPermission(permissionName, packageName, userId)
6101                == PackageManager.PERMISSION_GRANTED) {
6102            return false;
6103        }
6104
6105        final int flags;
6106
6107        final long identity = Binder.clearCallingIdentity();
6108        try {
6109            flags = getPermissionFlags(permissionName,
6110                    packageName, userId);
6111        } finally {
6112            Binder.restoreCallingIdentity(identity);
6113        }
6114
6115        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6116                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6117                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6118
6119        if ((flags & fixedFlags) != 0) {
6120            return false;
6121        }
6122
6123        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6124    }
6125
6126    @Override
6127    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6128        mContext.enforceCallingOrSelfPermission(
6129                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6130                "addOnPermissionsChangeListener");
6131
6132        synchronized (mPackages) {
6133            mOnPermissionChangeListeners.addListenerLocked(listener);
6134        }
6135    }
6136
6137    @Override
6138    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6139        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6140            throw new SecurityException("Instant applications don't have access to this method");
6141        }
6142        synchronized (mPackages) {
6143            mOnPermissionChangeListeners.removeListenerLocked(listener);
6144        }
6145    }
6146
6147    @Override
6148    public boolean isProtectedBroadcast(String actionName) {
6149        // allow instant applications
6150        synchronized (mProtectedBroadcasts) {
6151            if (mProtectedBroadcasts.contains(actionName)) {
6152                return true;
6153            } else if (actionName != null) {
6154                // TODO: remove these terrible hacks
6155                if (actionName.startsWith("android.net.netmon.lingerExpired")
6156                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6157                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6158                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6159                    return true;
6160                }
6161            }
6162        }
6163        return false;
6164    }
6165
6166    @Override
6167    public int checkSignatures(String pkg1, String pkg2) {
6168        synchronized (mPackages) {
6169            final PackageParser.Package p1 = mPackages.get(pkg1);
6170            final PackageParser.Package p2 = mPackages.get(pkg2);
6171            if (p1 == null || p1.mExtras == null
6172                    || p2 == null || p2.mExtras == null) {
6173                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6174            }
6175            final int callingUid = Binder.getCallingUid();
6176            final int callingUserId = UserHandle.getUserId(callingUid);
6177            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6178            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6179            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6180                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6181                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6182            }
6183            return compareSignatures(p1.mSignatures, p2.mSignatures);
6184        }
6185    }
6186
6187    @Override
6188    public int checkUidSignatures(int uid1, int uid2) {
6189        final int callingUid = Binder.getCallingUid();
6190        final int callingUserId = UserHandle.getUserId(callingUid);
6191        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6192        // Map to base uids.
6193        uid1 = UserHandle.getAppId(uid1);
6194        uid2 = UserHandle.getAppId(uid2);
6195        // reader
6196        synchronized (mPackages) {
6197            Signature[] s1;
6198            Signature[] s2;
6199            Object obj = mSettings.getUserIdLPr(uid1);
6200            if (obj != null) {
6201                if (obj instanceof SharedUserSetting) {
6202                    if (isCallerInstantApp) {
6203                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6204                    }
6205                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6206                } else if (obj instanceof PackageSetting) {
6207                    final PackageSetting ps = (PackageSetting) obj;
6208                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6209                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6210                    }
6211                    s1 = ps.signatures.mSignatures;
6212                } else {
6213                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6214                }
6215            } else {
6216                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6217            }
6218            obj = mSettings.getUserIdLPr(uid2);
6219            if (obj != null) {
6220                if (obj instanceof SharedUserSetting) {
6221                    if (isCallerInstantApp) {
6222                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6223                    }
6224                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6225                } else if (obj instanceof PackageSetting) {
6226                    final PackageSetting ps = (PackageSetting) obj;
6227                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6228                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6229                    }
6230                    s2 = ps.signatures.mSignatures;
6231                } else {
6232                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6233                }
6234            } else {
6235                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6236            }
6237            return compareSignatures(s1, s2);
6238        }
6239    }
6240
6241    /**
6242     * This method should typically only be used when granting or revoking
6243     * permissions, since the app may immediately restart after this call.
6244     * <p>
6245     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6246     * guard your work against the app being relaunched.
6247     */
6248    private void killUid(int appId, int userId, String reason) {
6249        final long identity = Binder.clearCallingIdentity();
6250        try {
6251            IActivityManager am = ActivityManager.getService();
6252            if (am != null) {
6253                try {
6254                    am.killUid(appId, userId, reason);
6255                } catch (RemoteException e) {
6256                    /* ignore - same process */
6257                }
6258            }
6259        } finally {
6260            Binder.restoreCallingIdentity(identity);
6261        }
6262    }
6263
6264    /**
6265     * Compares two sets of signatures. Returns:
6266     * <br />
6267     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6268     * <br />
6269     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6270     * <br />
6271     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6272     * <br />
6273     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6274     * <br />
6275     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6276     */
6277    static int compareSignatures(Signature[] s1, Signature[] s2) {
6278        if (s1 == null) {
6279            return s2 == null
6280                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6281                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6282        }
6283
6284        if (s2 == null) {
6285            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6286        }
6287
6288        if (s1.length != s2.length) {
6289            return PackageManager.SIGNATURE_NO_MATCH;
6290        }
6291
6292        // Since both signature sets are of size 1, we can compare without HashSets.
6293        if (s1.length == 1) {
6294            return s1[0].equals(s2[0]) ?
6295                    PackageManager.SIGNATURE_MATCH :
6296                    PackageManager.SIGNATURE_NO_MATCH;
6297        }
6298
6299        ArraySet<Signature> set1 = new ArraySet<Signature>();
6300        for (Signature sig : s1) {
6301            set1.add(sig);
6302        }
6303        ArraySet<Signature> set2 = new ArraySet<Signature>();
6304        for (Signature sig : s2) {
6305            set2.add(sig);
6306        }
6307        // Make sure s2 contains all signatures in s1.
6308        if (set1.equals(set2)) {
6309            return PackageManager.SIGNATURE_MATCH;
6310        }
6311        return PackageManager.SIGNATURE_NO_MATCH;
6312    }
6313
6314    /**
6315     * If the database version for this type of package (internal storage or
6316     * external storage) is less than the version where package signatures
6317     * were updated, return true.
6318     */
6319    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6320        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6321        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6322    }
6323
6324    /**
6325     * Used for backward compatibility to make sure any packages with
6326     * certificate chains get upgraded to the new style. {@code existingSigs}
6327     * will be in the old format (since they were stored on disk from before the
6328     * system upgrade) and {@code scannedSigs} will be in the newer format.
6329     */
6330    private int compareSignaturesCompat(PackageSignatures existingSigs,
6331            PackageParser.Package scannedPkg) {
6332        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6333            return PackageManager.SIGNATURE_NO_MATCH;
6334        }
6335
6336        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6337        for (Signature sig : existingSigs.mSignatures) {
6338            existingSet.add(sig);
6339        }
6340        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6341        for (Signature sig : scannedPkg.mSignatures) {
6342            try {
6343                Signature[] chainSignatures = sig.getChainSignatures();
6344                for (Signature chainSig : chainSignatures) {
6345                    scannedCompatSet.add(chainSig);
6346                }
6347            } catch (CertificateEncodingException e) {
6348                scannedCompatSet.add(sig);
6349            }
6350        }
6351        /*
6352         * Make sure the expanded scanned set contains all signatures in the
6353         * existing one.
6354         */
6355        if (scannedCompatSet.equals(existingSet)) {
6356            // Migrate the old signatures to the new scheme.
6357            existingSigs.assignSignatures(scannedPkg.mSignatures);
6358            // The new KeySets will be re-added later in the scanning process.
6359            synchronized (mPackages) {
6360                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6361            }
6362            return PackageManager.SIGNATURE_MATCH;
6363        }
6364        return PackageManager.SIGNATURE_NO_MATCH;
6365    }
6366
6367    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6368        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6369        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6370    }
6371
6372    private int compareSignaturesRecover(PackageSignatures existingSigs,
6373            PackageParser.Package scannedPkg) {
6374        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6375            return PackageManager.SIGNATURE_NO_MATCH;
6376        }
6377
6378        String msg = null;
6379        try {
6380            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6381                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6382                        + scannedPkg.packageName);
6383                return PackageManager.SIGNATURE_MATCH;
6384            }
6385        } catch (CertificateException e) {
6386            msg = e.getMessage();
6387        }
6388
6389        logCriticalInfo(Log.INFO,
6390                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6391        return PackageManager.SIGNATURE_NO_MATCH;
6392    }
6393
6394    @Override
6395    public List<String> getAllPackages() {
6396        final int callingUid = Binder.getCallingUid();
6397        final int callingUserId = UserHandle.getUserId(callingUid);
6398        synchronized (mPackages) {
6399            if (canViewInstantApps(callingUid, callingUserId)) {
6400                return new ArrayList<String>(mPackages.keySet());
6401            }
6402            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6403            final List<String> result = new ArrayList<>();
6404            if (instantAppPkgName != null) {
6405                // caller is an instant application; filter unexposed applications
6406                for (PackageParser.Package pkg : mPackages.values()) {
6407                    if (!pkg.visibleToInstantApps) {
6408                        continue;
6409                    }
6410                    result.add(pkg.packageName);
6411                }
6412            } else {
6413                // caller is a normal application; filter instant applications
6414                for (PackageParser.Package pkg : mPackages.values()) {
6415                    final PackageSetting ps =
6416                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6417                    if (ps != null
6418                            && ps.getInstantApp(callingUserId)
6419                            && !mInstantAppRegistry.isInstantAccessGranted(
6420                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6421                        continue;
6422                    }
6423                    result.add(pkg.packageName);
6424                }
6425            }
6426            return result;
6427        }
6428    }
6429
6430    @Override
6431    public String[] getPackagesForUid(int uid) {
6432        final int callingUid = Binder.getCallingUid();
6433        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6434        final int userId = UserHandle.getUserId(uid);
6435        uid = UserHandle.getAppId(uid);
6436        // reader
6437        synchronized (mPackages) {
6438            Object obj = mSettings.getUserIdLPr(uid);
6439            if (obj instanceof SharedUserSetting) {
6440                if (isCallerInstantApp) {
6441                    return null;
6442                }
6443                final SharedUserSetting sus = (SharedUserSetting) obj;
6444                final int N = sus.packages.size();
6445                String[] res = new String[N];
6446                final Iterator<PackageSetting> it = sus.packages.iterator();
6447                int i = 0;
6448                while (it.hasNext()) {
6449                    PackageSetting ps = it.next();
6450                    if (ps.getInstalled(userId)) {
6451                        res[i++] = ps.name;
6452                    } else {
6453                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6454                    }
6455                }
6456                return res;
6457            } else if (obj instanceof PackageSetting) {
6458                final PackageSetting ps = (PackageSetting) obj;
6459                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6460                    return new String[]{ps.name};
6461                }
6462            }
6463        }
6464        return null;
6465    }
6466
6467    @Override
6468    public String getNameForUid(int uid) {
6469        final int callingUid = Binder.getCallingUid();
6470        if (getInstantAppPackageName(callingUid) != null) {
6471            return null;
6472        }
6473        synchronized (mPackages) {
6474            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6475            if (obj instanceof SharedUserSetting) {
6476                final SharedUserSetting sus = (SharedUserSetting) obj;
6477                return sus.name + ":" + sus.userId;
6478            } else if (obj instanceof PackageSetting) {
6479                final PackageSetting ps = (PackageSetting) obj;
6480                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6481                    return null;
6482                }
6483                return ps.name;
6484            }
6485            return null;
6486        }
6487    }
6488
6489    @Override
6490    public String[] getNamesForUids(int[] uids) {
6491        if (uids == null || uids.length == 0) {
6492            return null;
6493        }
6494        final int callingUid = Binder.getCallingUid();
6495        if (getInstantAppPackageName(callingUid) != null) {
6496            return null;
6497        }
6498        final String[] names = new String[uids.length];
6499        synchronized (mPackages) {
6500            for (int i = uids.length - 1; i >= 0; i--) {
6501                final int uid = uids[i];
6502                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6503                if (obj instanceof SharedUserSetting) {
6504                    final SharedUserSetting sus = (SharedUserSetting) obj;
6505                    names[i] = "shared:" + sus.name;
6506                } else if (obj instanceof PackageSetting) {
6507                    final PackageSetting ps = (PackageSetting) obj;
6508                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6509                        names[i] = null;
6510                    } else {
6511                        names[i] = ps.name;
6512                    }
6513                } else {
6514                    names[i] = null;
6515                }
6516            }
6517        }
6518        return names;
6519    }
6520
6521    @Override
6522    public int getUidForSharedUser(String sharedUserName) {
6523        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6524            return -1;
6525        }
6526        if (sharedUserName == null) {
6527            return -1;
6528        }
6529        // reader
6530        synchronized (mPackages) {
6531            SharedUserSetting suid;
6532            try {
6533                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6534                if (suid != null) {
6535                    return suid.userId;
6536                }
6537            } catch (PackageManagerException ignore) {
6538                // can't happen, but, still need to catch it
6539            }
6540            return -1;
6541        }
6542    }
6543
6544    @Override
6545    public int getFlagsForUid(int uid) {
6546        final int callingUid = Binder.getCallingUid();
6547        if (getInstantAppPackageName(callingUid) != null) {
6548            return 0;
6549        }
6550        synchronized (mPackages) {
6551            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6552            if (obj instanceof SharedUserSetting) {
6553                final SharedUserSetting sus = (SharedUserSetting) obj;
6554                return sus.pkgFlags;
6555            } else if (obj instanceof PackageSetting) {
6556                final PackageSetting ps = (PackageSetting) obj;
6557                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6558                    return 0;
6559                }
6560                return ps.pkgFlags;
6561            }
6562        }
6563        return 0;
6564    }
6565
6566    @Override
6567    public int getPrivateFlagsForUid(int uid) {
6568        final int callingUid = Binder.getCallingUid();
6569        if (getInstantAppPackageName(callingUid) != null) {
6570            return 0;
6571        }
6572        synchronized (mPackages) {
6573            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6574            if (obj instanceof SharedUserSetting) {
6575                final SharedUserSetting sus = (SharedUserSetting) obj;
6576                return sus.pkgPrivateFlags;
6577            } else if (obj instanceof PackageSetting) {
6578                final PackageSetting ps = (PackageSetting) obj;
6579                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6580                    return 0;
6581                }
6582                return ps.pkgPrivateFlags;
6583            }
6584        }
6585        return 0;
6586    }
6587
6588    @Override
6589    public boolean isUidPrivileged(int uid) {
6590        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6591            return false;
6592        }
6593        uid = UserHandle.getAppId(uid);
6594        // reader
6595        synchronized (mPackages) {
6596            Object obj = mSettings.getUserIdLPr(uid);
6597            if (obj instanceof SharedUserSetting) {
6598                final SharedUserSetting sus = (SharedUserSetting) obj;
6599                final Iterator<PackageSetting> it = sus.packages.iterator();
6600                while (it.hasNext()) {
6601                    if (it.next().isPrivileged()) {
6602                        return true;
6603                    }
6604                }
6605            } else if (obj instanceof PackageSetting) {
6606                final PackageSetting ps = (PackageSetting) obj;
6607                return ps.isPrivileged();
6608            }
6609        }
6610        return false;
6611    }
6612
6613    @Override
6614    public String[] getAppOpPermissionPackages(String permissionName) {
6615        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6616            return null;
6617        }
6618        synchronized (mPackages) {
6619            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6620            if (pkgs == null) {
6621                return null;
6622            }
6623            return pkgs.toArray(new String[pkgs.size()]);
6624        }
6625    }
6626
6627    @Override
6628    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6629            int flags, int userId) {
6630        return resolveIntentInternal(
6631                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6632    }
6633
6634    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6635            int flags, int userId, boolean resolveForStart) {
6636        try {
6637            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6638
6639            if (!sUserManager.exists(userId)) return null;
6640            final int callingUid = Binder.getCallingUid();
6641            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6642            enforceCrossUserPermission(callingUid, userId,
6643                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6644
6645            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6646            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6647                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6648            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6649
6650            final ResolveInfo bestChoice =
6651                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6652            return bestChoice;
6653        } finally {
6654            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6655        }
6656    }
6657
6658    @Override
6659    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6660        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6661            throw new SecurityException(
6662                    "findPersistentPreferredActivity can only be run by the system");
6663        }
6664        if (!sUserManager.exists(userId)) {
6665            return null;
6666        }
6667        final int callingUid = Binder.getCallingUid();
6668        intent = updateIntentForResolve(intent);
6669        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6670        final int flags = updateFlagsForResolve(
6671                0, userId, intent, callingUid, false /*includeInstantApps*/);
6672        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6673                userId);
6674        synchronized (mPackages) {
6675            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6676                    userId);
6677        }
6678    }
6679
6680    @Override
6681    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6682            IntentFilter filter, int match, ComponentName activity) {
6683        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6684            return;
6685        }
6686        final int userId = UserHandle.getCallingUserId();
6687        if (DEBUG_PREFERRED) {
6688            Log.v(TAG, "setLastChosenActivity intent=" + intent
6689                + " resolvedType=" + resolvedType
6690                + " flags=" + flags
6691                + " filter=" + filter
6692                + " match=" + match
6693                + " activity=" + activity);
6694            filter.dump(new PrintStreamPrinter(System.out), "    ");
6695        }
6696        intent.setComponent(null);
6697        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6698                userId);
6699        // Find any earlier preferred or last chosen entries and nuke them
6700        findPreferredActivity(intent, resolvedType,
6701                flags, query, 0, false, true, false, userId);
6702        // Add the new activity as the last chosen for this filter
6703        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6704                "Setting last chosen");
6705    }
6706
6707    @Override
6708    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6709        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6710            return null;
6711        }
6712        final int userId = UserHandle.getCallingUserId();
6713        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6714        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6715                userId);
6716        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6717                false, false, false, userId);
6718    }
6719
6720    /**
6721     * Returns whether or not instant apps have been disabled remotely.
6722     */
6723    private boolean isEphemeralDisabled() {
6724        return mEphemeralAppsDisabled;
6725    }
6726
6727    private boolean isInstantAppAllowed(
6728            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6729            boolean skipPackageCheck) {
6730        if (mInstantAppResolverConnection == null) {
6731            return false;
6732        }
6733        if (mInstantAppInstallerActivity == null) {
6734            return false;
6735        }
6736        if (intent.getComponent() != null) {
6737            return false;
6738        }
6739        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6740            return false;
6741        }
6742        if (!skipPackageCheck && intent.getPackage() != null) {
6743            return false;
6744        }
6745        final boolean isWebUri = hasWebURI(intent);
6746        if (!isWebUri || intent.getData().getHost() == null) {
6747            return false;
6748        }
6749        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6750        // Or if there's already an ephemeral app installed that handles the action
6751        synchronized (mPackages) {
6752            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6753            for (int n = 0; n < count; n++) {
6754                final ResolveInfo info = resolvedActivities.get(n);
6755                final String packageName = info.activityInfo.packageName;
6756                final PackageSetting ps = mSettings.mPackages.get(packageName);
6757                if (ps != null) {
6758                    // only check domain verification status if the app is not a browser
6759                    if (!info.handleAllWebDataURI) {
6760                        // Try to get the status from User settings first
6761                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6762                        final int status = (int) (packedStatus >> 32);
6763                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6764                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6765                            if (DEBUG_EPHEMERAL) {
6766                                Slog.v(TAG, "DENY instant app;"
6767                                    + " pkg: " + packageName + ", status: " + status);
6768                            }
6769                            return false;
6770                        }
6771                    }
6772                    if (ps.getInstantApp(userId)) {
6773                        if (DEBUG_EPHEMERAL) {
6774                            Slog.v(TAG, "DENY instant app installed;"
6775                                    + " pkg: " + packageName);
6776                        }
6777                        return false;
6778                    }
6779                }
6780            }
6781        }
6782        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6783        return true;
6784    }
6785
6786    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6787            Intent origIntent, String resolvedType, String callingPackage,
6788            Bundle verificationBundle, int userId) {
6789        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6790                new InstantAppRequest(responseObj, origIntent, resolvedType,
6791                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6792        mHandler.sendMessage(msg);
6793    }
6794
6795    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6796            int flags, List<ResolveInfo> query, int userId) {
6797        if (query != null) {
6798            final int N = query.size();
6799            if (N == 1) {
6800                return query.get(0);
6801            } else if (N > 1) {
6802                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6803                // If there is more than one activity with the same priority,
6804                // then let the user decide between them.
6805                ResolveInfo r0 = query.get(0);
6806                ResolveInfo r1 = query.get(1);
6807                if (DEBUG_INTENT_MATCHING || debug) {
6808                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6809                            + r1.activityInfo.name + "=" + r1.priority);
6810                }
6811                // If the first activity has a higher priority, or a different
6812                // default, then it is always desirable to pick it.
6813                if (r0.priority != r1.priority
6814                        || r0.preferredOrder != r1.preferredOrder
6815                        || r0.isDefault != r1.isDefault) {
6816                    return query.get(0);
6817                }
6818                // If we have saved a preference for a preferred activity for
6819                // this Intent, use that.
6820                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6821                        flags, query, r0.priority, true, false, debug, userId);
6822                if (ri != null) {
6823                    return ri;
6824                }
6825                // If we have an ephemeral app, use it
6826                for (int i = 0; i < N; i++) {
6827                    ri = query.get(i);
6828                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6829                        final String packageName = ri.activityInfo.packageName;
6830                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6831                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6832                        final int status = (int)(packedStatus >> 32);
6833                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6834                            return ri;
6835                        }
6836                    }
6837                }
6838                ri = new ResolveInfo(mResolveInfo);
6839                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6840                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6841                // If all of the options come from the same package, show the application's
6842                // label and icon instead of the generic resolver's.
6843                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6844                // and then throw away the ResolveInfo itself, meaning that the caller loses
6845                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6846                // a fallback for this case; we only set the target package's resources on
6847                // the ResolveInfo, not the ActivityInfo.
6848                final String intentPackage = intent.getPackage();
6849                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6850                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6851                    ri.resolvePackageName = intentPackage;
6852                    if (userNeedsBadging(userId)) {
6853                        ri.noResourceId = true;
6854                    } else {
6855                        ri.icon = appi.icon;
6856                    }
6857                    ri.iconResourceId = appi.icon;
6858                    ri.labelRes = appi.labelRes;
6859                }
6860                ri.activityInfo.applicationInfo = new ApplicationInfo(
6861                        ri.activityInfo.applicationInfo);
6862                if (userId != 0) {
6863                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6864                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6865                }
6866                // Make sure that the resolver is displayable in car mode
6867                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6868                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6869                return ri;
6870            }
6871        }
6872        return null;
6873    }
6874
6875    /**
6876     * Return true if the given list is not empty and all of its contents have
6877     * an activityInfo with the given package name.
6878     */
6879    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6880        if (ArrayUtils.isEmpty(list)) {
6881            return false;
6882        }
6883        for (int i = 0, N = list.size(); i < N; i++) {
6884            final ResolveInfo ri = list.get(i);
6885            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6886            if (ai == null || !packageName.equals(ai.packageName)) {
6887                return false;
6888            }
6889        }
6890        return true;
6891    }
6892
6893    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6894            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6895        final int N = query.size();
6896        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6897                .get(userId);
6898        // Get the list of persistent preferred activities that handle the intent
6899        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6900        List<PersistentPreferredActivity> pprefs = ppir != null
6901                ? ppir.queryIntent(intent, resolvedType,
6902                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6903                        userId)
6904                : null;
6905        if (pprefs != null && pprefs.size() > 0) {
6906            final int M = pprefs.size();
6907            for (int i=0; i<M; i++) {
6908                final PersistentPreferredActivity ppa = pprefs.get(i);
6909                if (DEBUG_PREFERRED || debug) {
6910                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6911                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6912                            + "\n  component=" + ppa.mComponent);
6913                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6914                }
6915                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6916                        flags | MATCH_DISABLED_COMPONENTS, userId);
6917                if (DEBUG_PREFERRED || debug) {
6918                    Slog.v(TAG, "Found persistent preferred activity:");
6919                    if (ai != null) {
6920                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6921                    } else {
6922                        Slog.v(TAG, "  null");
6923                    }
6924                }
6925                if (ai == null) {
6926                    // This previously registered persistent preferred activity
6927                    // component is no longer known. Ignore it and do NOT remove it.
6928                    continue;
6929                }
6930                for (int j=0; j<N; j++) {
6931                    final ResolveInfo ri = query.get(j);
6932                    if (!ri.activityInfo.applicationInfo.packageName
6933                            .equals(ai.applicationInfo.packageName)) {
6934                        continue;
6935                    }
6936                    if (!ri.activityInfo.name.equals(ai.name)) {
6937                        continue;
6938                    }
6939                    //  Found a persistent preference that can handle the intent.
6940                    if (DEBUG_PREFERRED || debug) {
6941                        Slog.v(TAG, "Returning persistent preferred activity: " +
6942                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6943                    }
6944                    return ri;
6945                }
6946            }
6947        }
6948        return null;
6949    }
6950
6951    // TODO: handle preferred activities missing while user has amnesia
6952    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6953            List<ResolveInfo> query, int priority, boolean always,
6954            boolean removeMatches, boolean debug, int userId) {
6955        if (!sUserManager.exists(userId)) return null;
6956        final int callingUid = Binder.getCallingUid();
6957        flags = updateFlagsForResolve(
6958                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6959        intent = updateIntentForResolve(intent);
6960        // writer
6961        synchronized (mPackages) {
6962            // Try to find a matching persistent preferred activity.
6963            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6964                    debug, userId);
6965
6966            // If a persistent preferred activity matched, use it.
6967            if (pri != null) {
6968                return pri;
6969            }
6970
6971            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6972            // Get the list of preferred activities that handle the intent
6973            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6974            List<PreferredActivity> prefs = pir != null
6975                    ? pir.queryIntent(intent, resolvedType,
6976                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6977                            userId)
6978                    : null;
6979            if (prefs != null && prefs.size() > 0) {
6980                boolean changed = false;
6981                try {
6982                    // First figure out how good the original match set is.
6983                    // We will only allow preferred activities that came
6984                    // from the same match quality.
6985                    int match = 0;
6986
6987                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6988
6989                    final int N = query.size();
6990                    for (int j=0; j<N; j++) {
6991                        final ResolveInfo ri = query.get(j);
6992                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6993                                + ": 0x" + Integer.toHexString(match));
6994                        if (ri.match > match) {
6995                            match = ri.match;
6996                        }
6997                    }
6998
6999                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
7000                            + Integer.toHexString(match));
7001
7002                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7003                    final int M = prefs.size();
7004                    for (int i=0; i<M; i++) {
7005                        final PreferredActivity pa = prefs.get(i);
7006                        if (DEBUG_PREFERRED || debug) {
7007                            Slog.v(TAG, "Checking PreferredActivity ds="
7008                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7009                                    + "\n  component=" + pa.mPref.mComponent);
7010                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7011                        }
7012                        if (pa.mPref.mMatch != match) {
7013                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7014                                    + Integer.toHexString(pa.mPref.mMatch));
7015                            continue;
7016                        }
7017                        // If it's not an "always" type preferred activity and that's what we're
7018                        // looking for, skip it.
7019                        if (always && !pa.mPref.mAlways) {
7020                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7021                            continue;
7022                        }
7023                        final ActivityInfo ai = getActivityInfo(
7024                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7025                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7026                                userId);
7027                        if (DEBUG_PREFERRED || debug) {
7028                            Slog.v(TAG, "Found preferred activity:");
7029                            if (ai != null) {
7030                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7031                            } else {
7032                                Slog.v(TAG, "  null");
7033                            }
7034                        }
7035                        if (ai == null) {
7036                            // This previously registered preferred activity
7037                            // component is no longer known.  Most likely an update
7038                            // to the app was installed and in the new version this
7039                            // component no longer exists.  Clean it up by removing
7040                            // it from the preferred activities list, and skip it.
7041                            Slog.w(TAG, "Removing dangling preferred activity: "
7042                                    + pa.mPref.mComponent);
7043                            pir.removeFilter(pa);
7044                            changed = true;
7045                            continue;
7046                        }
7047                        for (int j=0; j<N; j++) {
7048                            final ResolveInfo ri = query.get(j);
7049                            if (!ri.activityInfo.applicationInfo.packageName
7050                                    .equals(ai.applicationInfo.packageName)) {
7051                                continue;
7052                            }
7053                            if (!ri.activityInfo.name.equals(ai.name)) {
7054                                continue;
7055                            }
7056
7057                            if (removeMatches) {
7058                                pir.removeFilter(pa);
7059                                changed = true;
7060                                if (DEBUG_PREFERRED) {
7061                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7062                                }
7063                                break;
7064                            }
7065
7066                            // Okay we found a previously set preferred or last chosen app.
7067                            // If the result set is different from when this
7068                            // was created, and is not a subset of the preferred set, we need to
7069                            // clear it and re-ask the user their preference, if we're looking for
7070                            // an "always" type entry.
7071                            if (always && !pa.mPref.sameSet(query)) {
7072                                if (pa.mPref.isSuperset(query)) {
7073                                    // some components of the set are no longer present in
7074                                    // the query, but the preferred activity can still be reused
7075                                    if (DEBUG_PREFERRED) {
7076                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7077                                                + " still valid as only non-preferred components"
7078                                                + " were removed for " + intent + " type "
7079                                                + resolvedType);
7080                                    }
7081                                    // remove obsolete components and re-add the up-to-date filter
7082                                    PreferredActivity freshPa = new PreferredActivity(pa,
7083                                            pa.mPref.mMatch,
7084                                            pa.mPref.discardObsoleteComponents(query),
7085                                            pa.mPref.mComponent,
7086                                            pa.mPref.mAlways);
7087                                    pir.removeFilter(pa);
7088                                    pir.addFilter(freshPa);
7089                                    changed = true;
7090                                } else {
7091                                    Slog.i(TAG,
7092                                            "Result set changed, dropping preferred activity for "
7093                                                    + intent + " type " + resolvedType);
7094                                    if (DEBUG_PREFERRED) {
7095                                        Slog.v(TAG, "Removing preferred activity since set changed "
7096                                                + pa.mPref.mComponent);
7097                                    }
7098                                    pir.removeFilter(pa);
7099                                    // Re-add the filter as a "last chosen" entry (!always)
7100                                    PreferredActivity lastChosen = new PreferredActivity(
7101                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7102                                    pir.addFilter(lastChosen);
7103                                    changed = true;
7104                                    return null;
7105                                }
7106                            }
7107
7108                            // Yay! Either the set matched or we're looking for the last chosen
7109                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7110                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7111                            return ri;
7112                        }
7113                    }
7114                } finally {
7115                    if (changed) {
7116                        if (DEBUG_PREFERRED) {
7117                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7118                        }
7119                        scheduleWritePackageRestrictionsLocked(userId);
7120                    }
7121                }
7122            }
7123        }
7124        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7125        return null;
7126    }
7127
7128    /*
7129     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7130     */
7131    @Override
7132    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7133            int targetUserId) {
7134        mContext.enforceCallingOrSelfPermission(
7135                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7136        List<CrossProfileIntentFilter> matches =
7137                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7138        if (matches != null) {
7139            int size = matches.size();
7140            for (int i = 0; i < size; i++) {
7141                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7142            }
7143        }
7144        if (hasWebURI(intent)) {
7145            // cross-profile app linking works only towards the parent.
7146            final int callingUid = Binder.getCallingUid();
7147            final UserInfo parent = getProfileParent(sourceUserId);
7148            synchronized(mPackages) {
7149                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7150                        false /*includeInstantApps*/);
7151                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7152                        intent, resolvedType, flags, sourceUserId, parent.id);
7153                return xpDomainInfo != null;
7154            }
7155        }
7156        return false;
7157    }
7158
7159    private UserInfo getProfileParent(int userId) {
7160        final long identity = Binder.clearCallingIdentity();
7161        try {
7162            return sUserManager.getProfileParent(userId);
7163        } finally {
7164            Binder.restoreCallingIdentity(identity);
7165        }
7166    }
7167
7168    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7169            String resolvedType, int userId) {
7170        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7171        if (resolver != null) {
7172            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7173        }
7174        return null;
7175    }
7176
7177    @Override
7178    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7179            String resolvedType, int flags, int userId) {
7180        try {
7181            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7182
7183            return new ParceledListSlice<>(
7184                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7185        } finally {
7186            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7187        }
7188    }
7189
7190    /**
7191     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7192     * instant, returns {@code null}.
7193     */
7194    private String getInstantAppPackageName(int callingUid) {
7195        synchronized (mPackages) {
7196            // If the caller is an isolated app use the owner's uid for the lookup.
7197            if (Process.isIsolated(callingUid)) {
7198                callingUid = mIsolatedOwners.get(callingUid);
7199            }
7200            final int appId = UserHandle.getAppId(callingUid);
7201            final Object obj = mSettings.getUserIdLPr(appId);
7202            if (obj instanceof PackageSetting) {
7203                final PackageSetting ps = (PackageSetting) obj;
7204                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7205                return isInstantApp ? ps.pkg.packageName : null;
7206            }
7207        }
7208        return null;
7209    }
7210
7211    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7212            String resolvedType, int flags, int userId) {
7213        return queryIntentActivitiesInternal(
7214                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7215                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7216    }
7217
7218    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7219            String resolvedType, int flags, int filterCallingUid, int userId,
7220            boolean resolveForStart, boolean allowDynamicSplits) {
7221        if (!sUserManager.exists(userId)) return Collections.emptyList();
7222        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7223        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7224                false /* requireFullPermission */, false /* checkShell */,
7225                "query intent activities");
7226        final String pkgName = intent.getPackage();
7227        ComponentName comp = intent.getComponent();
7228        if (comp == null) {
7229            if (intent.getSelector() != null) {
7230                intent = intent.getSelector();
7231                comp = intent.getComponent();
7232            }
7233        }
7234
7235        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7236                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7237        if (comp != null) {
7238            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7239            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7240            if (ai != null) {
7241                // When specifying an explicit component, we prevent the activity from being
7242                // used when either 1) the calling package is normal and the activity is within
7243                // an ephemeral application or 2) the calling package is ephemeral and the
7244                // activity is not visible to ephemeral applications.
7245                final boolean matchInstantApp =
7246                        (flags & PackageManager.MATCH_INSTANT) != 0;
7247                final boolean matchVisibleToInstantAppOnly =
7248                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7249                final boolean matchExplicitlyVisibleOnly =
7250                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7251                final boolean isCallerInstantApp =
7252                        instantAppPkgName != null;
7253                final boolean isTargetSameInstantApp =
7254                        comp.getPackageName().equals(instantAppPkgName);
7255                final boolean isTargetInstantApp =
7256                        (ai.applicationInfo.privateFlags
7257                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7258                final boolean isTargetVisibleToInstantApp =
7259                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7260                final boolean isTargetExplicitlyVisibleToInstantApp =
7261                        isTargetVisibleToInstantApp
7262                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7263                final boolean isTargetHiddenFromInstantApp =
7264                        !isTargetVisibleToInstantApp
7265                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7266                final boolean blockResolution =
7267                        !isTargetSameInstantApp
7268                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7269                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7270                                        && isTargetHiddenFromInstantApp));
7271                if (!blockResolution) {
7272                    final ResolveInfo ri = new ResolveInfo();
7273                    ri.activityInfo = ai;
7274                    list.add(ri);
7275                }
7276            }
7277            return applyPostResolutionFilter(
7278                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7279        }
7280
7281        // reader
7282        boolean sortResult = false;
7283        boolean addEphemeral = false;
7284        List<ResolveInfo> result;
7285        final boolean ephemeralDisabled = isEphemeralDisabled();
7286        synchronized (mPackages) {
7287            if (pkgName == null) {
7288                List<CrossProfileIntentFilter> matchingFilters =
7289                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7290                // Check for results that need to skip the current profile.
7291                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7292                        resolvedType, flags, userId);
7293                if (xpResolveInfo != null) {
7294                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7295                    xpResult.add(xpResolveInfo);
7296                    return applyPostResolutionFilter(
7297                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7298                            allowDynamicSplits, filterCallingUid, userId);
7299                }
7300
7301                // Check for results in the current profile.
7302                result = filterIfNotSystemUser(mActivities.queryIntent(
7303                        intent, resolvedType, flags, userId), userId);
7304                addEphemeral = !ephemeralDisabled
7305                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7306                // Check for cross profile results.
7307                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7308                xpResolveInfo = queryCrossProfileIntents(
7309                        matchingFilters, intent, resolvedType, flags, userId,
7310                        hasNonNegativePriorityResult);
7311                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7312                    boolean isVisibleToUser = filterIfNotSystemUser(
7313                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7314                    if (isVisibleToUser) {
7315                        result.add(xpResolveInfo);
7316                        sortResult = true;
7317                    }
7318                }
7319                if (hasWebURI(intent)) {
7320                    CrossProfileDomainInfo xpDomainInfo = null;
7321                    final UserInfo parent = getProfileParent(userId);
7322                    if (parent != null) {
7323                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7324                                flags, userId, parent.id);
7325                    }
7326                    if (xpDomainInfo != null) {
7327                        if (xpResolveInfo != null) {
7328                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7329                            // in the result.
7330                            result.remove(xpResolveInfo);
7331                        }
7332                        if (result.size() == 0 && !addEphemeral) {
7333                            // No result in current profile, but found candidate in parent user.
7334                            // And we are not going to add emphemeral app, so we can return the
7335                            // result straight away.
7336                            result.add(xpDomainInfo.resolveInfo);
7337                            return applyPostResolutionFilter(result, instantAppPkgName,
7338                                    allowDynamicSplits, filterCallingUid, userId);
7339                        }
7340                    } else if (result.size() <= 1 && !addEphemeral) {
7341                        // No result in parent user and <= 1 result in current profile, and we
7342                        // are not going to add emphemeral app, so we can return the result without
7343                        // further processing.
7344                        return applyPostResolutionFilter(result, instantAppPkgName,
7345                                allowDynamicSplits, filterCallingUid, userId);
7346                    }
7347                    // We have more than one candidate (combining results from current and parent
7348                    // profile), so we need filtering and sorting.
7349                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7350                            intent, flags, result, xpDomainInfo, userId);
7351                    sortResult = true;
7352                }
7353            } else {
7354                final PackageParser.Package pkg = mPackages.get(pkgName);
7355                result = null;
7356                if (pkg != null) {
7357                    result = filterIfNotSystemUser(
7358                            mActivities.queryIntentForPackage(
7359                                    intent, resolvedType, flags, pkg.activities, userId),
7360                            userId);
7361                }
7362                if (result == null || result.size() == 0) {
7363                    // the caller wants to resolve for a particular package; however, there
7364                    // were no installed results, so, try to find an ephemeral result
7365                    addEphemeral = !ephemeralDisabled
7366                            && isInstantAppAllowed(
7367                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7368                    if (result == null) {
7369                        result = new ArrayList<>();
7370                    }
7371                }
7372            }
7373        }
7374        if (addEphemeral) {
7375            result = maybeAddInstantAppInstaller(
7376                    result, intent, resolvedType, flags, userId, resolveForStart);
7377        }
7378        if (sortResult) {
7379            Collections.sort(result, mResolvePrioritySorter);
7380        }
7381        return applyPostResolutionFilter(
7382                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7383    }
7384
7385    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7386            String resolvedType, int flags, int userId, boolean resolveForStart) {
7387        // first, check to see if we've got an instant app already installed
7388        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7389        ResolveInfo localInstantApp = null;
7390        boolean blockResolution = false;
7391        if (!alreadyResolvedLocally) {
7392            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7393                    flags
7394                        | PackageManager.GET_RESOLVED_FILTER
7395                        | PackageManager.MATCH_INSTANT
7396                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7397                    userId);
7398            for (int i = instantApps.size() - 1; i >= 0; --i) {
7399                final ResolveInfo info = instantApps.get(i);
7400                final String packageName = info.activityInfo.packageName;
7401                final PackageSetting ps = mSettings.mPackages.get(packageName);
7402                if (ps.getInstantApp(userId)) {
7403                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7404                    final int status = (int)(packedStatus >> 32);
7405                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7406                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7407                        // there's a local instant application installed, but, the user has
7408                        // chosen to never use it; skip resolution and don't acknowledge
7409                        // an instant application is even available
7410                        if (DEBUG_EPHEMERAL) {
7411                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7412                        }
7413                        blockResolution = true;
7414                        break;
7415                    } else {
7416                        // we have a locally installed instant application; skip resolution
7417                        // but acknowledge there's an instant application available
7418                        if (DEBUG_EPHEMERAL) {
7419                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7420                        }
7421                        localInstantApp = info;
7422                        break;
7423                    }
7424                }
7425            }
7426        }
7427        // no app installed, let's see if one's available
7428        AuxiliaryResolveInfo auxiliaryResponse = null;
7429        if (!blockResolution) {
7430            if (localInstantApp == null) {
7431                // we don't have an instant app locally, resolve externally
7432                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7433                final InstantAppRequest requestObject = new InstantAppRequest(
7434                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7435                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7436                        resolveForStart);
7437                auxiliaryResponse =
7438                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7439                                mContext, mInstantAppResolverConnection, requestObject);
7440                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7441            } else {
7442                // we have an instant application locally, but, we can't admit that since
7443                // callers shouldn't be able to determine prior browsing. create a dummy
7444                // auxiliary response so the downstream code behaves as if there's an
7445                // instant application available externally. when it comes time to start
7446                // the instant application, we'll do the right thing.
7447                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7448                auxiliaryResponse = new AuxiliaryResolveInfo(
7449                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7450                        ai.versionCode, null /*failureIntent*/);
7451            }
7452        }
7453        if (auxiliaryResponse != null) {
7454            if (DEBUG_EPHEMERAL) {
7455                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7456            }
7457            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7458            final PackageSetting ps =
7459                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7460            if (ps != null) {
7461                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7462                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7463                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7464                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7465                // make sure this resolver is the default
7466                ephemeralInstaller.isDefault = true;
7467                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7468                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7469                // add a non-generic filter
7470                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7471                ephemeralInstaller.filter.addDataPath(
7472                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7473                ephemeralInstaller.isInstantAppAvailable = true;
7474                result.add(ephemeralInstaller);
7475            }
7476        }
7477        return result;
7478    }
7479
7480    private static class CrossProfileDomainInfo {
7481        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7482        ResolveInfo resolveInfo;
7483        /* Best domain verification status of the activities found in the other profile */
7484        int bestDomainVerificationStatus;
7485    }
7486
7487    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7488            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7489        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7490                sourceUserId)) {
7491            return null;
7492        }
7493        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7494                resolvedType, flags, parentUserId);
7495
7496        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7497            return null;
7498        }
7499        CrossProfileDomainInfo result = null;
7500        int size = resultTargetUser.size();
7501        for (int i = 0; i < size; i++) {
7502            ResolveInfo riTargetUser = resultTargetUser.get(i);
7503            // Intent filter verification is only for filters that specify a host. So don't return
7504            // those that handle all web uris.
7505            if (riTargetUser.handleAllWebDataURI) {
7506                continue;
7507            }
7508            String packageName = riTargetUser.activityInfo.packageName;
7509            PackageSetting ps = mSettings.mPackages.get(packageName);
7510            if (ps == null) {
7511                continue;
7512            }
7513            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7514            int status = (int)(verificationState >> 32);
7515            if (result == null) {
7516                result = new CrossProfileDomainInfo();
7517                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7518                        sourceUserId, parentUserId);
7519                result.bestDomainVerificationStatus = status;
7520            } else {
7521                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7522                        result.bestDomainVerificationStatus);
7523            }
7524        }
7525        // Don't consider matches with status NEVER across profiles.
7526        if (result != null && result.bestDomainVerificationStatus
7527                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7528            return null;
7529        }
7530        return result;
7531    }
7532
7533    /**
7534     * Verification statuses are ordered from the worse to the best, except for
7535     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7536     */
7537    private int bestDomainVerificationStatus(int status1, int status2) {
7538        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7539            return status2;
7540        }
7541        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7542            return status1;
7543        }
7544        return (int) MathUtils.max(status1, status2);
7545    }
7546
7547    private boolean isUserEnabled(int userId) {
7548        long callingId = Binder.clearCallingIdentity();
7549        try {
7550            UserInfo userInfo = sUserManager.getUserInfo(userId);
7551            return userInfo != null && userInfo.isEnabled();
7552        } finally {
7553            Binder.restoreCallingIdentity(callingId);
7554        }
7555    }
7556
7557    /**
7558     * Filter out activities with systemUserOnly flag set, when current user is not System.
7559     *
7560     * @return filtered list
7561     */
7562    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7563        if (userId == UserHandle.USER_SYSTEM) {
7564            return resolveInfos;
7565        }
7566        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7567            ResolveInfo info = resolveInfos.get(i);
7568            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7569                resolveInfos.remove(i);
7570            }
7571        }
7572        return resolveInfos;
7573    }
7574
7575    /**
7576     * Filters out ephemeral activities.
7577     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7578     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7579     *
7580     * @param resolveInfos The pre-filtered list of resolved activities
7581     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7582     *          is performed.
7583     * @return A filtered list of resolved activities.
7584     */
7585    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7586            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7587        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7588            final ResolveInfo info = resolveInfos.get(i);
7589            // allow activities that are defined in the provided package
7590            if (allowDynamicSplits
7591                    && info.activityInfo.splitName != null
7592                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7593                            info.activityInfo.splitName)) {
7594                // requested activity is defined in a split that hasn't been installed yet.
7595                // add the installer to the resolve list
7596                if (DEBUG_INSTALL) {
7597                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7598                }
7599                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7600                final ComponentName installFailureActivity = findInstallFailureActivity(
7601                        info.activityInfo.packageName,  filterCallingUid, userId);
7602                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7603                        info.activityInfo.packageName, info.activityInfo.splitName,
7604                        installFailureActivity,
7605                        info.activityInfo.applicationInfo.versionCode,
7606                        null /*failureIntent*/);
7607                // make sure this resolver is the default
7608                installerInfo.isDefault = true;
7609                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7610                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7611                // add a non-generic filter
7612                installerInfo.filter = new IntentFilter();
7613                // load resources from the correct package
7614                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7615                resolveInfos.set(i, installerInfo);
7616                continue;
7617            }
7618            // caller is a full app, don't need to apply any other filtering
7619            if (ephemeralPkgName == null) {
7620                continue;
7621            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7622                // caller is same app; don't need to apply any other filtering
7623                continue;
7624            }
7625            // allow activities that have been explicitly exposed to ephemeral apps
7626            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7627            if (!isEphemeralApp
7628                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7629                continue;
7630            }
7631            resolveInfos.remove(i);
7632        }
7633        return resolveInfos;
7634    }
7635
7636    /**
7637     * Returns the activity component that can handle install failures.
7638     * <p>By default, the instant application installer handles failures. However, an
7639     * application may want to handle failures on its own. Applications do this by
7640     * creating an activity with an intent filter that handles the action
7641     * {@link Intent#ACTION_INSTALL_FAILURE}.
7642     */
7643    private @Nullable ComponentName findInstallFailureActivity(
7644            String packageName, int filterCallingUid, int userId) {
7645        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7646        failureActivityIntent.setPackage(packageName);
7647        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7648        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7649                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7650                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7651        final int NR = result.size();
7652        if (NR > 0) {
7653            for (int i = 0; i < NR; i++) {
7654                final ResolveInfo info = result.get(i);
7655                if (info.activityInfo.splitName != null) {
7656                    continue;
7657                }
7658                return new ComponentName(packageName, info.activityInfo.name);
7659            }
7660        }
7661        return null;
7662    }
7663
7664    /**
7665     * @param resolveInfos list of resolve infos in descending priority order
7666     * @return if the list contains a resolve info with non-negative priority
7667     */
7668    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7669        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7670    }
7671
7672    private static boolean hasWebURI(Intent intent) {
7673        if (intent.getData() == null) {
7674            return false;
7675        }
7676        final String scheme = intent.getScheme();
7677        if (TextUtils.isEmpty(scheme)) {
7678            return false;
7679        }
7680        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7681    }
7682
7683    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7684            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7685            int userId) {
7686        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7687
7688        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7689            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7690                    candidates.size());
7691        }
7692
7693        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7694        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7695        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7696        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7697        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7698        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7699
7700        synchronized (mPackages) {
7701            final int count = candidates.size();
7702            // First, try to use linked apps. Partition the candidates into four lists:
7703            // one for the final results, one for the "do not use ever", one for "undefined status"
7704            // and finally one for "browser app type".
7705            for (int n=0; n<count; n++) {
7706                ResolveInfo info = candidates.get(n);
7707                String packageName = info.activityInfo.packageName;
7708                PackageSetting ps = mSettings.mPackages.get(packageName);
7709                if (ps != null) {
7710                    // Add to the special match all list (Browser use case)
7711                    if (info.handleAllWebDataURI) {
7712                        matchAllList.add(info);
7713                        continue;
7714                    }
7715                    // Try to get the status from User settings first
7716                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7717                    int status = (int)(packedStatus >> 32);
7718                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7719                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7720                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7721                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7722                                    + " : linkgen=" + linkGeneration);
7723                        }
7724                        // Use link-enabled generation as preferredOrder, i.e.
7725                        // prefer newly-enabled over earlier-enabled.
7726                        info.preferredOrder = linkGeneration;
7727                        alwaysList.add(info);
7728                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7729                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7730                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7731                        }
7732                        neverList.add(info);
7733                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7734                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7735                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7736                        }
7737                        alwaysAskList.add(info);
7738                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7739                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7740                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7741                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7742                        }
7743                        undefinedList.add(info);
7744                    }
7745                }
7746            }
7747
7748            // We'll want to include browser possibilities in a few cases
7749            boolean includeBrowser = false;
7750
7751            // First try to add the "always" resolution(s) for the current user, if any
7752            if (alwaysList.size() > 0) {
7753                result.addAll(alwaysList);
7754            } else {
7755                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7756                result.addAll(undefinedList);
7757                // Maybe add one for the other profile.
7758                if (xpDomainInfo != null && (
7759                        xpDomainInfo.bestDomainVerificationStatus
7760                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7761                    result.add(xpDomainInfo.resolveInfo);
7762                }
7763                includeBrowser = true;
7764            }
7765
7766            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7767            // If there were 'always' entries their preferred order has been set, so we also
7768            // back that off to make the alternatives equivalent
7769            if (alwaysAskList.size() > 0) {
7770                for (ResolveInfo i : result) {
7771                    i.preferredOrder = 0;
7772                }
7773                result.addAll(alwaysAskList);
7774                includeBrowser = true;
7775            }
7776
7777            if (includeBrowser) {
7778                // Also add browsers (all of them or only the default one)
7779                if (DEBUG_DOMAIN_VERIFICATION) {
7780                    Slog.v(TAG, "   ...including browsers in candidate set");
7781                }
7782                if ((matchFlags & MATCH_ALL) != 0) {
7783                    result.addAll(matchAllList);
7784                } else {
7785                    // Browser/generic handling case.  If there's a default browser, go straight
7786                    // to that (but only if there is no other higher-priority match).
7787                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7788                    int maxMatchPrio = 0;
7789                    ResolveInfo defaultBrowserMatch = null;
7790                    final int numCandidates = matchAllList.size();
7791                    for (int n = 0; n < numCandidates; n++) {
7792                        ResolveInfo info = matchAllList.get(n);
7793                        // track the highest overall match priority...
7794                        if (info.priority > maxMatchPrio) {
7795                            maxMatchPrio = info.priority;
7796                        }
7797                        // ...and the highest-priority default browser match
7798                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7799                            if (defaultBrowserMatch == null
7800                                    || (defaultBrowserMatch.priority < info.priority)) {
7801                                if (debug) {
7802                                    Slog.v(TAG, "Considering default browser match " + info);
7803                                }
7804                                defaultBrowserMatch = info;
7805                            }
7806                        }
7807                    }
7808                    if (defaultBrowserMatch != null
7809                            && defaultBrowserMatch.priority >= maxMatchPrio
7810                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7811                    {
7812                        if (debug) {
7813                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7814                        }
7815                        result.add(defaultBrowserMatch);
7816                    } else {
7817                        result.addAll(matchAllList);
7818                    }
7819                }
7820
7821                // If there is nothing selected, add all candidates and remove the ones that the user
7822                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7823                if (result.size() == 0) {
7824                    result.addAll(candidates);
7825                    result.removeAll(neverList);
7826                }
7827            }
7828        }
7829        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7830            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7831                    result.size());
7832            for (ResolveInfo info : result) {
7833                Slog.v(TAG, "  + " + info.activityInfo);
7834            }
7835        }
7836        return result;
7837    }
7838
7839    // Returns a packed value as a long:
7840    //
7841    // high 'int'-sized word: link status: undefined/ask/never/always.
7842    // low 'int'-sized word: relative priority among 'always' results.
7843    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7844        long result = ps.getDomainVerificationStatusForUser(userId);
7845        // if none available, get the master status
7846        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7847            if (ps.getIntentFilterVerificationInfo() != null) {
7848                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7849            }
7850        }
7851        return result;
7852    }
7853
7854    private ResolveInfo querySkipCurrentProfileIntents(
7855            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7856            int flags, int sourceUserId) {
7857        if (matchingFilters != null) {
7858            int size = matchingFilters.size();
7859            for (int i = 0; i < size; i ++) {
7860                CrossProfileIntentFilter filter = matchingFilters.get(i);
7861                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7862                    // Checking if there are activities in the target user that can handle the
7863                    // intent.
7864                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7865                            resolvedType, flags, sourceUserId);
7866                    if (resolveInfo != null) {
7867                        return resolveInfo;
7868                    }
7869                }
7870            }
7871        }
7872        return null;
7873    }
7874
7875    // Return matching ResolveInfo in target user if any.
7876    private ResolveInfo queryCrossProfileIntents(
7877            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7878            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7879        if (matchingFilters != null) {
7880            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7881            // match the same intent. For performance reasons, it is better not to
7882            // run queryIntent twice for the same userId
7883            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7884            int size = matchingFilters.size();
7885            for (int i = 0; i < size; i++) {
7886                CrossProfileIntentFilter filter = matchingFilters.get(i);
7887                int targetUserId = filter.getTargetUserId();
7888                boolean skipCurrentProfile =
7889                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7890                boolean skipCurrentProfileIfNoMatchFound =
7891                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7892                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7893                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7894                    // Checking if there are activities in the target user that can handle the
7895                    // intent.
7896                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7897                            resolvedType, flags, sourceUserId);
7898                    if (resolveInfo != null) return resolveInfo;
7899                    alreadyTriedUserIds.put(targetUserId, true);
7900                }
7901            }
7902        }
7903        return null;
7904    }
7905
7906    /**
7907     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7908     * will forward the intent to the filter's target user.
7909     * Otherwise, returns null.
7910     */
7911    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7912            String resolvedType, int flags, int sourceUserId) {
7913        int targetUserId = filter.getTargetUserId();
7914        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7915                resolvedType, flags, targetUserId);
7916        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7917            // If all the matches in the target profile are suspended, return null.
7918            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7919                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7920                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7921                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7922                            targetUserId);
7923                }
7924            }
7925        }
7926        return null;
7927    }
7928
7929    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7930            int sourceUserId, int targetUserId) {
7931        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7932        long ident = Binder.clearCallingIdentity();
7933        boolean targetIsProfile;
7934        try {
7935            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7936        } finally {
7937            Binder.restoreCallingIdentity(ident);
7938        }
7939        String className;
7940        if (targetIsProfile) {
7941            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7942        } else {
7943            className = FORWARD_INTENT_TO_PARENT;
7944        }
7945        ComponentName forwardingActivityComponentName = new ComponentName(
7946                mAndroidApplication.packageName, className);
7947        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7948                sourceUserId);
7949        if (!targetIsProfile) {
7950            forwardingActivityInfo.showUserIcon = targetUserId;
7951            forwardingResolveInfo.noResourceId = true;
7952        }
7953        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7954        forwardingResolveInfo.priority = 0;
7955        forwardingResolveInfo.preferredOrder = 0;
7956        forwardingResolveInfo.match = 0;
7957        forwardingResolveInfo.isDefault = true;
7958        forwardingResolveInfo.filter = filter;
7959        forwardingResolveInfo.targetUserId = targetUserId;
7960        return forwardingResolveInfo;
7961    }
7962
7963    @Override
7964    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7965            Intent[] specifics, String[] specificTypes, Intent intent,
7966            String resolvedType, int flags, int userId) {
7967        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7968                specificTypes, intent, resolvedType, flags, userId));
7969    }
7970
7971    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7972            Intent[] specifics, String[] specificTypes, Intent intent,
7973            String resolvedType, int flags, int userId) {
7974        if (!sUserManager.exists(userId)) return Collections.emptyList();
7975        final int callingUid = Binder.getCallingUid();
7976        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7977                false /*includeInstantApps*/);
7978        enforceCrossUserPermission(callingUid, userId,
7979                false /*requireFullPermission*/, false /*checkShell*/,
7980                "query intent activity options");
7981        final String resultsAction = intent.getAction();
7982
7983        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7984                | PackageManager.GET_RESOLVED_FILTER, userId);
7985
7986        if (DEBUG_INTENT_MATCHING) {
7987            Log.v(TAG, "Query " + intent + ": " + results);
7988        }
7989
7990        int specificsPos = 0;
7991        int N;
7992
7993        // todo: note that the algorithm used here is O(N^2).  This
7994        // isn't a problem in our current environment, but if we start running
7995        // into situations where we have more than 5 or 10 matches then this
7996        // should probably be changed to something smarter...
7997
7998        // First we go through and resolve each of the specific items
7999        // that were supplied, taking care of removing any corresponding
8000        // duplicate items in the generic resolve list.
8001        if (specifics != null) {
8002            for (int i=0; i<specifics.length; i++) {
8003                final Intent sintent = specifics[i];
8004                if (sintent == null) {
8005                    continue;
8006                }
8007
8008                if (DEBUG_INTENT_MATCHING) {
8009                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8010                }
8011
8012                String action = sintent.getAction();
8013                if (resultsAction != null && resultsAction.equals(action)) {
8014                    // If this action was explicitly requested, then don't
8015                    // remove things that have it.
8016                    action = null;
8017                }
8018
8019                ResolveInfo ri = null;
8020                ActivityInfo ai = null;
8021
8022                ComponentName comp = sintent.getComponent();
8023                if (comp == null) {
8024                    ri = resolveIntent(
8025                        sintent,
8026                        specificTypes != null ? specificTypes[i] : null,
8027                            flags, userId);
8028                    if (ri == null) {
8029                        continue;
8030                    }
8031                    if (ri == mResolveInfo) {
8032                        // ACK!  Must do something better with this.
8033                    }
8034                    ai = ri.activityInfo;
8035                    comp = new ComponentName(ai.applicationInfo.packageName,
8036                            ai.name);
8037                } else {
8038                    ai = getActivityInfo(comp, flags, userId);
8039                    if (ai == null) {
8040                        continue;
8041                    }
8042                }
8043
8044                // Look for any generic query activities that are duplicates
8045                // of this specific one, and remove them from the results.
8046                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8047                N = results.size();
8048                int j;
8049                for (j=specificsPos; j<N; j++) {
8050                    ResolveInfo sri = results.get(j);
8051                    if ((sri.activityInfo.name.equals(comp.getClassName())
8052                            && sri.activityInfo.applicationInfo.packageName.equals(
8053                                    comp.getPackageName()))
8054                        || (action != null && sri.filter.matchAction(action))) {
8055                        results.remove(j);
8056                        if (DEBUG_INTENT_MATCHING) Log.v(
8057                            TAG, "Removing duplicate item from " + j
8058                            + " due to specific " + specificsPos);
8059                        if (ri == null) {
8060                            ri = sri;
8061                        }
8062                        j--;
8063                        N--;
8064                    }
8065                }
8066
8067                // Add this specific item to its proper place.
8068                if (ri == null) {
8069                    ri = new ResolveInfo();
8070                    ri.activityInfo = ai;
8071                }
8072                results.add(specificsPos, ri);
8073                ri.specificIndex = i;
8074                specificsPos++;
8075            }
8076        }
8077
8078        // Now we go through the remaining generic results and remove any
8079        // duplicate actions that are found here.
8080        N = results.size();
8081        for (int i=specificsPos; i<N-1; i++) {
8082            final ResolveInfo rii = results.get(i);
8083            if (rii.filter == null) {
8084                continue;
8085            }
8086
8087            // Iterate over all of the actions of this result's intent
8088            // filter...  typically this should be just one.
8089            final Iterator<String> it = rii.filter.actionsIterator();
8090            if (it == null) {
8091                continue;
8092            }
8093            while (it.hasNext()) {
8094                final String action = it.next();
8095                if (resultsAction != null && resultsAction.equals(action)) {
8096                    // If this action was explicitly requested, then don't
8097                    // remove things that have it.
8098                    continue;
8099                }
8100                for (int j=i+1; j<N; j++) {
8101                    final ResolveInfo rij = results.get(j);
8102                    if (rij.filter != null && rij.filter.hasAction(action)) {
8103                        results.remove(j);
8104                        if (DEBUG_INTENT_MATCHING) Log.v(
8105                            TAG, "Removing duplicate item from " + j
8106                            + " due to action " + action + " at " + i);
8107                        j--;
8108                        N--;
8109                    }
8110                }
8111            }
8112
8113            // If the caller didn't request filter information, drop it now
8114            // so we don't have to marshall/unmarshall it.
8115            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8116                rii.filter = null;
8117            }
8118        }
8119
8120        // Filter out the caller activity if so requested.
8121        if (caller != null) {
8122            N = results.size();
8123            for (int i=0; i<N; i++) {
8124                ActivityInfo ainfo = results.get(i).activityInfo;
8125                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8126                        && caller.getClassName().equals(ainfo.name)) {
8127                    results.remove(i);
8128                    break;
8129                }
8130            }
8131        }
8132
8133        // If the caller didn't request filter information,
8134        // drop them now so we don't have to
8135        // marshall/unmarshall it.
8136        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8137            N = results.size();
8138            for (int i=0; i<N; i++) {
8139                results.get(i).filter = null;
8140            }
8141        }
8142
8143        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8144        return results;
8145    }
8146
8147    @Override
8148    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8149            String resolvedType, int flags, int userId) {
8150        return new ParceledListSlice<>(
8151                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8152                        false /*allowDynamicSplits*/));
8153    }
8154
8155    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8156            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8157        if (!sUserManager.exists(userId)) return Collections.emptyList();
8158        final int callingUid = Binder.getCallingUid();
8159        enforceCrossUserPermission(callingUid, userId,
8160                false /*requireFullPermission*/, false /*checkShell*/,
8161                "query intent receivers");
8162        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8163        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8164                false /*includeInstantApps*/);
8165        ComponentName comp = intent.getComponent();
8166        if (comp == null) {
8167            if (intent.getSelector() != null) {
8168                intent = intent.getSelector();
8169                comp = intent.getComponent();
8170            }
8171        }
8172        if (comp != null) {
8173            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8174            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8175            if (ai != null) {
8176                // When specifying an explicit component, we prevent the activity from being
8177                // used when either 1) the calling package is normal and the activity is within
8178                // an instant application or 2) the calling package is ephemeral and the
8179                // activity is not visible to instant applications.
8180                final boolean matchInstantApp =
8181                        (flags & PackageManager.MATCH_INSTANT) != 0;
8182                final boolean matchVisibleToInstantAppOnly =
8183                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8184                final boolean matchExplicitlyVisibleOnly =
8185                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8186                final boolean isCallerInstantApp =
8187                        instantAppPkgName != null;
8188                final boolean isTargetSameInstantApp =
8189                        comp.getPackageName().equals(instantAppPkgName);
8190                final boolean isTargetInstantApp =
8191                        (ai.applicationInfo.privateFlags
8192                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8193                final boolean isTargetVisibleToInstantApp =
8194                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8195                final boolean isTargetExplicitlyVisibleToInstantApp =
8196                        isTargetVisibleToInstantApp
8197                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8198                final boolean isTargetHiddenFromInstantApp =
8199                        !isTargetVisibleToInstantApp
8200                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8201                final boolean blockResolution =
8202                        !isTargetSameInstantApp
8203                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8204                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8205                                        && isTargetHiddenFromInstantApp));
8206                if (!blockResolution) {
8207                    ResolveInfo ri = new ResolveInfo();
8208                    ri.activityInfo = ai;
8209                    list.add(ri);
8210                }
8211            }
8212            return applyPostResolutionFilter(
8213                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8214        }
8215
8216        // reader
8217        synchronized (mPackages) {
8218            String pkgName = intent.getPackage();
8219            if (pkgName == null) {
8220                final List<ResolveInfo> result =
8221                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8222                return applyPostResolutionFilter(
8223                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8224            }
8225            final PackageParser.Package pkg = mPackages.get(pkgName);
8226            if (pkg != null) {
8227                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8228                        intent, resolvedType, flags, pkg.receivers, userId);
8229                return applyPostResolutionFilter(
8230                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8231            }
8232            return Collections.emptyList();
8233        }
8234    }
8235
8236    @Override
8237    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8238        final int callingUid = Binder.getCallingUid();
8239        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8240    }
8241
8242    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8243            int userId, int callingUid) {
8244        if (!sUserManager.exists(userId)) return null;
8245        flags = updateFlagsForResolve(
8246                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8247        List<ResolveInfo> query = queryIntentServicesInternal(
8248                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8249        if (query != null) {
8250            if (query.size() >= 1) {
8251                // If there is more than one service with the same priority,
8252                // just arbitrarily pick the first one.
8253                return query.get(0);
8254            }
8255        }
8256        return null;
8257    }
8258
8259    @Override
8260    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8261            String resolvedType, int flags, int userId) {
8262        final int callingUid = Binder.getCallingUid();
8263        return new ParceledListSlice<>(queryIntentServicesInternal(
8264                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8265    }
8266
8267    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8268            String resolvedType, int flags, int userId, int callingUid,
8269            boolean includeInstantApps) {
8270        if (!sUserManager.exists(userId)) return Collections.emptyList();
8271        enforceCrossUserPermission(callingUid, userId,
8272                false /*requireFullPermission*/, false /*checkShell*/,
8273                "query intent receivers");
8274        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8275        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8276        ComponentName comp = intent.getComponent();
8277        if (comp == null) {
8278            if (intent.getSelector() != null) {
8279                intent = intent.getSelector();
8280                comp = intent.getComponent();
8281            }
8282        }
8283        if (comp != null) {
8284            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8285            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8286            if (si != null) {
8287                // When specifying an explicit component, we prevent the service from being
8288                // used when either 1) the service is in an instant application and the
8289                // caller is not the same instant application or 2) the calling package is
8290                // ephemeral and the activity is not visible to ephemeral applications.
8291                final boolean matchInstantApp =
8292                        (flags & PackageManager.MATCH_INSTANT) != 0;
8293                final boolean matchVisibleToInstantAppOnly =
8294                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8295                final boolean isCallerInstantApp =
8296                        instantAppPkgName != null;
8297                final boolean isTargetSameInstantApp =
8298                        comp.getPackageName().equals(instantAppPkgName);
8299                final boolean isTargetInstantApp =
8300                        (si.applicationInfo.privateFlags
8301                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8302                final boolean isTargetHiddenFromInstantApp =
8303                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8304                final boolean blockResolution =
8305                        !isTargetSameInstantApp
8306                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8307                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8308                                        && isTargetHiddenFromInstantApp));
8309                if (!blockResolution) {
8310                    final ResolveInfo ri = new ResolveInfo();
8311                    ri.serviceInfo = si;
8312                    list.add(ri);
8313                }
8314            }
8315            return list;
8316        }
8317
8318        // reader
8319        synchronized (mPackages) {
8320            String pkgName = intent.getPackage();
8321            if (pkgName == null) {
8322                return applyPostServiceResolutionFilter(
8323                        mServices.queryIntent(intent, resolvedType, flags, userId),
8324                        instantAppPkgName);
8325            }
8326            final PackageParser.Package pkg = mPackages.get(pkgName);
8327            if (pkg != null) {
8328                return applyPostServiceResolutionFilter(
8329                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8330                                userId),
8331                        instantAppPkgName);
8332            }
8333            return Collections.emptyList();
8334        }
8335    }
8336
8337    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8338            String instantAppPkgName) {
8339        if (instantAppPkgName == null) {
8340            return resolveInfos;
8341        }
8342        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8343            final ResolveInfo info = resolveInfos.get(i);
8344            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8345            // allow services that are defined in the provided package
8346            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8347                if (info.serviceInfo.splitName != null
8348                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8349                                info.serviceInfo.splitName)) {
8350                    // requested service is defined in a split that hasn't been installed yet.
8351                    // add the installer to the resolve list
8352                    if (DEBUG_EPHEMERAL) {
8353                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8354                    }
8355                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8356                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8357                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8358                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8359                            null /*failureIntent*/);
8360                    // make sure this resolver is the default
8361                    installerInfo.isDefault = true;
8362                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8363                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8364                    // add a non-generic filter
8365                    installerInfo.filter = new IntentFilter();
8366                    // load resources from the correct package
8367                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8368                    resolveInfos.set(i, installerInfo);
8369                }
8370                continue;
8371            }
8372            // allow services that have been explicitly exposed to ephemeral apps
8373            if (!isEphemeralApp
8374                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8375                continue;
8376            }
8377            resolveInfos.remove(i);
8378        }
8379        return resolveInfos;
8380    }
8381
8382    @Override
8383    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8384            String resolvedType, int flags, int userId) {
8385        return new ParceledListSlice<>(
8386                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8387    }
8388
8389    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8390            Intent intent, String resolvedType, int flags, int userId) {
8391        if (!sUserManager.exists(userId)) return Collections.emptyList();
8392        final int callingUid = Binder.getCallingUid();
8393        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8394        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8395                false /*includeInstantApps*/);
8396        ComponentName comp = intent.getComponent();
8397        if (comp == null) {
8398            if (intent.getSelector() != null) {
8399                intent = intent.getSelector();
8400                comp = intent.getComponent();
8401            }
8402        }
8403        if (comp != null) {
8404            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8405            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8406            if (pi != null) {
8407                // When specifying an explicit component, we prevent the provider from being
8408                // used when either 1) the provider is in an instant application and the
8409                // caller is not the same instant application or 2) the calling package is an
8410                // instant application and the provider is not visible to instant applications.
8411                final boolean matchInstantApp =
8412                        (flags & PackageManager.MATCH_INSTANT) != 0;
8413                final boolean matchVisibleToInstantAppOnly =
8414                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8415                final boolean isCallerInstantApp =
8416                        instantAppPkgName != null;
8417                final boolean isTargetSameInstantApp =
8418                        comp.getPackageName().equals(instantAppPkgName);
8419                final boolean isTargetInstantApp =
8420                        (pi.applicationInfo.privateFlags
8421                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8422                final boolean isTargetHiddenFromInstantApp =
8423                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8424                final boolean blockResolution =
8425                        !isTargetSameInstantApp
8426                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8427                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8428                                        && isTargetHiddenFromInstantApp));
8429                if (!blockResolution) {
8430                    final ResolveInfo ri = new ResolveInfo();
8431                    ri.providerInfo = pi;
8432                    list.add(ri);
8433                }
8434            }
8435            return list;
8436        }
8437
8438        // reader
8439        synchronized (mPackages) {
8440            String pkgName = intent.getPackage();
8441            if (pkgName == null) {
8442                return applyPostContentProviderResolutionFilter(
8443                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8444                        instantAppPkgName);
8445            }
8446            final PackageParser.Package pkg = mPackages.get(pkgName);
8447            if (pkg != null) {
8448                return applyPostContentProviderResolutionFilter(
8449                        mProviders.queryIntentForPackage(
8450                        intent, resolvedType, flags, pkg.providers, userId),
8451                        instantAppPkgName);
8452            }
8453            return Collections.emptyList();
8454        }
8455    }
8456
8457    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8458            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8459        if (instantAppPkgName == null) {
8460            return resolveInfos;
8461        }
8462        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8463            final ResolveInfo info = resolveInfos.get(i);
8464            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8465            // allow providers that are defined in the provided package
8466            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8467                if (info.providerInfo.splitName != null
8468                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8469                                info.providerInfo.splitName)) {
8470                    // requested provider is defined in a split that hasn't been installed yet.
8471                    // add the installer to the resolve list
8472                    if (DEBUG_EPHEMERAL) {
8473                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8474                    }
8475                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8476                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8477                            info.providerInfo.packageName, info.providerInfo.splitName,
8478                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8479                            null /*failureIntent*/);
8480                    // make sure this resolver is the default
8481                    installerInfo.isDefault = true;
8482                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8483                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8484                    // add a non-generic filter
8485                    installerInfo.filter = new IntentFilter();
8486                    // load resources from the correct package
8487                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8488                    resolveInfos.set(i, installerInfo);
8489                }
8490                continue;
8491            }
8492            // allow providers that have been explicitly exposed to instant applications
8493            if (!isEphemeralApp
8494                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8495                continue;
8496            }
8497            resolveInfos.remove(i);
8498        }
8499        return resolveInfos;
8500    }
8501
8502    @Override
8503    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8504        final int callingUid = Binder.getCallingUid();
8505        if (getInstantAppPackageName(callingUid) != null) {
8506            return ParceledListSlice.emptyList();
8507        }
8508        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8509        flags = updateFlagsForPackage(flags, userId, null);
8510        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8511        enforceCrossUserPermission(callingUid, userId,
8512                true /* requireFullPermission */, false /* checkShell */,
8513                "get installed packages");
8514
8515        // writer
8516        synchronized (mPackages) {
8517            ArrayList<PackageInfo> list;
8518            if (listUninstalled) {
8519                list = new ArrayList<>(mSettings.mPackages.size());
8520                for (PackageSetting ps : mSettings.mPackages.values()) {
8521                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8522                        continue;
8523                    }
8524                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8525                        continue;
8526                    }
8527                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8528                    if (pi != null) {
8529                        list.add(pi);
8530                    }
8531                }
8532            } else {
8533                list = new ArrayList<>(mPackages.size());
8534                for (PackageParser.Package p : mPackages.values()) {
8535                    final PackageSetting ps = (PackageSetting) p.mExtras;
8536                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8537                        continue;
8538                    }
8539                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8540                        continue;
8541                    }
8542                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8543                            p.mExtras, flags, userId);
8544                    if (pi != null) {
8545                        list.add(pi);
8546                    }
8547                }
8548            }
8549
8550            return new ParceledListSlice<>(list);
8551        }
8552    }
8553
8554    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8555            String[] permissions, boolean[] tmp, int flags, int userId) {
8556        int numMatch = 0;
8557        final PermissionsState permissionsState = ps.getPermissionsState();
8558        for (int i=0; i<permissions.length; i++) {
8559            final String permission = permissions[i];
8560            if (permissionsState.hasPermission(permission, userId)) {
8561                tmp[i] = true;
8562                numMatch++;
8563            } else {
8564                tmp[i] = false;
8565            }
8566        }
8567        if (numMatch == 0) {
8568            return;
8569        }
8570        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8571
8572        // The above might return null in cases of uninstalled apps or install-state
8573        // skew across users/profiles.
8574        if (pi != null) {
8575            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8576                if (numMatch == permissions.length) {
8577                    pi.requestedPermissions = permissions;
8578                } else {
8579                    pi.requestedPermissions = new String[numMatch];
8580                    numMatch = 0;
8581                    for (int i=0; i<permissions.length; i++) {
8582                        if (tmp[i]) {
8583                            pi.requestedPermissions[numMatch] = permissions[i];
8584                            numMatch++;
8585                        }
8586                    }
8587                }
8588            }
8589            list.add(pi);
8590        }
8591    }
8592
8593    @Override
8594    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8595            String[] permissions, int flags, int userId) {
8596        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8597        flags = updateFlagsForPackage(flags, userId, permissions);
8598        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8599                true /* requireFullPermission */, false /* checkShell */,
8600                "get packages holding permissions");
8601        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8602
8603        // writer
8604        synchronized (mPackages) {
8605            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8606            boolean[] tmpBools = new boolean[permissions.length];
8607            if (listUninstalled) {
8608                for (PackageSetting ps : mSettings.mPackages.values()) {
8609                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8610                            userId);
8611                }
8612            } else {
8613                for (PackageParser.Package pkg : mPackages.values()) {
8614                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8615                    if (ps != null) {
8616                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8617                                userId);
8618                    }
8619                }
8620            }
8621
8622            return new ParceledListSlice<PackageInfo>(list);
8623        }
8624    }
8625
8626    @Override
8627    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8628        final int callingUid = Binder.getCallingUid();
8629        if (getInstantAppPackageName(callingUid) != null) {
8630            return ParceledListSlice.emptyList();
8631        }
8632        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8633        flags = updateFlagsForApplication(flags, userId, null);
8634        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8635
8636        // writer
8637        synchronized (mPackages) {
8638            ArrayList<ApplicationInfo> list;
8639            if (listUninstalled) {
8640                list = new ArrayList<>(mSettings.mPackages.size());
8641                for (PackageSetting ps : mSettings.mPackages.values()) {
8642                    ApplicationInfo ai;
8643                    int effectiveFlags = flags;
8644                    if (ps.isSystem()) {
8645                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8646                    }
8647                    if (ps.pkg != null) {
8648                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8649                            continue;
8650                        }
8651                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8652                            continue;
8653                        }
8654                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8655                                ps.readUserState(userId), userId);
8656                        if (ai != null) {
8657                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8658                        }
8659                    } else {
8660                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8661                        // and already converts to externally visible package name
8662                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8663                                callingUid, effectiveFlags, userId);
8664                    }
8665                    if (ai != null) {
8666                        list.add(ai);
8667                    }
8668                }
8669            } else {
8670                list = new ArrayList<>(mPackages.size());
8671                for (PackageParser.Package p : mPackages.values()) {
8672                    if (p.mExtras != null) {
8673                        PackageSetting ps = (PackageSetting) p.mExtras;
8674                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8675                            continue;
8676                        }
8677                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8678                            continue;
8679                        }
8680                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8681                                ps.readUserState(userId), userId);
8682                        if (ai != null) {
8683                            ai.packageName = resolveExternalPackageNameLPr(p);
8684                            list.add(ai);
8685                        }
8686                    }
8687                }
8688            }
8689
8690            return new ParceledListSlice<>(list);
8691        }
8692    }
8693
8694    @Override
8695    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8696        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8697            return null;
8698        }
8699        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8700            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8701                    "getEphemeralApplications");
8702        }
8703        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8704                true /* requireFullPermission */, false /* checkShell */,
8705                "getEphemeralApplications");
8706        synchronized (mPackages) {
8707            List<InstantAppInfo> instantApps = mInstantAppRegistry
8708                    .getInstantAppsLPr(userId);
8709            if (instantApps != null) {
8710                return new ParceledListSlice<>(instantApps);
8711            }
8712        }
8713        return null;
8714    }
8715
8716    @Override
8717    public boolean isInstantApp(String packageName, int userId) {
8718        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8719                true /* requireFullPermission */, false /* checkShell */,
8720                "isInstantApp");
8721        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8722            return false;
8723        }
8724
8725        synchronized (mPackages) {
8726            int callingUid = Binder.getCallingUid();
8727            if (Process.isIsolated(callingUid)) {
8728                callingUid = mIsolatedOwners.get(callingUid);
8729            }
8730            final PackageSetting ps = mSettings.mPackages.get(packageName);
8731            PackageParser.Package pkg = mPackages.get(packageName);
8732            final boolean returnAllowed =
8733                    ps != null
8734                    && (isCallerSameApp(packageName, callingUid)
8735                            || canViewInstantApps(callingUid, userId)
8736                            || mInstantAppRegistry.isInstantAccessGranted(
8737                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8738            if (returnAllowed) {
8739                return ps.getInstantApp(userId);
8740            }
8741        }
8742        return false;
8743    }
8744
8745    @Override
8746    public byte[] getInstantAppCookie(String packageName, int userId) {
8747        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8748            return null;
8749        }
8750
8751        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8752                true /* requireFullPermission */, false /* checkShell */,
8753                "getInstantAppCookie");
8754        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8755            return null;
8756        }
8757        synchronized (mPackages) {
8758            return mInstantAppRegistry.getInstantAppCookieLPw(
8759                    packageName, userId);
8760        }
8761    }
8762
8763    @Override
8764    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8765        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8766            return true;
8767        }
8768
8769        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8770                true /* requireFullPermission */, true /* checkShell */,
8771                "setInstantAppCookie");
8772        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8773            return false;
8774        }
8775        synchronized (mPackages) {
8776            return mInstantAppRegistry.setInstantAppCookieLPw(
8777                    packageName, cookie, userId);
8778        }
8779    }
8780
8781    @Override
8782    public Bitmap getInstantAppIcon(String packageName, int userId) {
8783        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8784            return null;
8785        }
8786
8787        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8788            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8789                    "getInstantAppIcon");
8790        }
8791        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8792                true /* requireFullPermission */, false /* checkShell */,
8793                "getInstantAppIcon");
8794
8795        synchronized (mPackages) {
8796            return mInstantAppRegistry.getInstantAppIconLPw(
8797                    packageName, userId);
8798        }
8799    }
8800
8801    private boolean isCallerSameApp(String packageName, int uid) {
8802        PackageParser.Package pkg = mPackages.get(packageName);
8803        return pkg != null
8804                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8805    }
8806
8807    @Override
8808    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8809        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8810            return ParceledListSlice.emptyList();
8811        }
8812        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8813    }
8814
8815    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8816        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8817
8818        // reader
8819        synchronized (mPackages) {
8820            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8821            final int userId = UserHandle.getCallingUserId();
8822            while (i.hasNext()) {
8823                final PackageParser.Package p = i.next();
8824                if (p.applicationInfo == null) continue;
8825
8826                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8827                        && !p.applicationInfo.isDirectBootAware();
8828                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8829                        && p.applicationInfo.isDirectBootAware();
8830
8831                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8832                        && (!mSafeMode || isSystemApp(p))
8833                        && (matchesUnaware || matchesAware)) {
8834                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8835                    if (ps != null) {
8836                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8837                                ps.readUserState(userId), userId);
8838                        if (ai != null) {
8839                            finalList.add(ai);
8840                        }
8841                    }
8842                }
8843            }
8844        }
8845
8846        return finalList;
8847    }
8848
8849    @Override
8850    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8851        if (!sUserManager.exists(userId)) return null;
8852        flags = updateFlagsForComponent(flags, userId, name);
8853        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8854        // reader
8855        synchronized (mPackages) {
8856            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8857            PackageSetting ps = provider != null
8858                    ? mSettings.mPackages.get(provider.owner.packageName)
8859                    : null;
8860            if (ps != null) {
8861                final boolean isInstantApp = ps.getInstantApp(userId);
8862                // normal application; filter out instant application provider
8863                if (instantAppPkgName == null && isInstantApp) {
8864                    return null;
8865                }
8866                // instant application; filter out other instant applications
8867                if (instantAppPkgName != null
8868                        && isInstantApp
8869                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8870                    return null;
8871                }
8872                // instant application; filter out non-exposed provider
8873                if (instantAppPkgName != null
8874                        && !isInstantApp
8875                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8876                    return null;
8877                }
8878                // provider not enabled
8879                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8880                    return null;
8881                }
8882                return PackageParser.generateProviderInfo(
8883                        provider, flags, ps.readUserState(userId), userId);
8884            }
8885            return null;
8886        }
8887    }
8888
8889    /**
8890     * @deprecated
8891     */
8892    @Deprecated
8893    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8894        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8895            return;
8896        }
8897        // reader
8898        synchronized (mPackages) {
8899            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8900                    .entrySet().iterator();
8901            final int userId = UserHandle.getCallingUserId();
8902            while (i.hasNext()) {
8903                Map.Entry<String, PackageParser.Provider> entry = i.next();
8904                PackageParser.Provider p = entry.getValue();
8905                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8906
8907                if (ps != null && p.syncable
8908                        && (!mSafeMode || (p.info.applicationInfo.flags
8909                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8910                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8911                            ps.readUserState(userId), userId);
8912                    if (info != null) {
8913                        outNames.add(entry.getKey());
8914                        outInfo.add(info);
8915                    }
8916                }
8917            }
8918        }
8919    }
8920
8921    @Override
8922    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8923            int uid, int flags, String metaDataKey) {
8924        final int callingUid = Binder.getCallingUid();
8925        final int userId = processName != null ? UserHandle.getUserId(uid)
8926                : UserHandle.getCallingUserId();
8927        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8928        flags = updateFlagsForComponent(flags, userId, processName);
8929        ArrayList<ProviderInfo> finalList = null;
8930        // reader
8931        synchronized (mPackages) {
8932            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8933            while (i.hasNext()) {
8934                final PackageParser.Provider p = i.next();
8935                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8936                if (ps != null && p.info.authority != null
8937                        && (processName == null
8938                                || (p.info.processName.equals(processName)
8939                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8940                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8941
8942                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8943                    // parameter.
8944                    if (metaDataKey != null
8945                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8946                        continue;
8947                    }
8948                    final ComponentName component =
8949                            new ComponentName(p.info.packageName, p.info.name);
8950                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8951                        continue;
8952                    }
8953                    if (finalList == null) {
8954                        finalList = new ArrayList<ProviderInfo>(3);
8955                    }
8956                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8957                            ps.readUserState(userId), userId);
8958                    if (info != null) {
8959                        finalList.add(info);
8960                    }
8961                }
8962            }
8963        }
8964
8965        if (finalList != null) {
8966            Collections.sort(finalList, mProviderInitOrderSorter);
8967            return new ParceledListSlice<ProviderInfo>(finalList);
8968        }
8969
8970        return ParceledListSlice.emptyList();
8971    }
8972
8973    @Override
8974    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8975        // reader
8976        synchronized (mPackages) {
8977            final int callingUid = Binder.getCallingUid();
8978            final int callingUserId = UserHandle.getUserId(callingUid);
8979            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8980            if (ps == null) return null;
8981            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8982                return null;
8983            }
8984            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8985            return PackageParser.generateInstrumentationInfo(i, flags);
8986        }
8987    }
8988
8989    @Override
8990    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8991            String targetPackage, int flags) {
8992        final int callingUid = Binder.getCallingUid();
8993        final int callingUserId = UserHandle.getUserId(callingUid);
8994        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8995        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8996            return ParceledListSlice.emptyList();
8997        }
8998        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8999    }
9000
9001    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
9002            int flags) {
9003        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9004
9005        // reader
9006        synchronized (mPackages) {
9007            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9008            while (i.hasNext()) {
9009                final PackageParser.Instrumentation p = i.next();
9010                if (targetPackage == null
9011                        || targetPackage.equals(p.info.targetPackage)) {
9012                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9013                            flags);
9014                    if (ii != null) {
9015                        finalList.add(ii);
9016                    }
9017                }
9018            }
9019        }
9020
9021        return finalList;
9022    }
9023
9024    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9025        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9026        try {
9027            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9028        } finally {
9029            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9030        }
9031    }
9032
9033    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9034        final File[] files = dir.listFiles();
9035        if (ArrayUtils.isEmpty(files)) {
9036            Log.d(TAG, "No files in app dir " + dir);
9037            return;
9038        }
9039
9040        if (DEBUG_PACKAGE_SCANNING) {
9041            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9042                    + " flags=0x" + Integer.toHexString(parseFlags));
9043        }
9044        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9045                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9046                mParallelPackageParserCallback);
9047
9048        // Submit files for parsing in parallel
9049        int fileCount = 0;
9050        for (File file : files) {
9051            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9052                    && !PackageInstallerService.isStageName(file.getName());
9053            if (!isPackage) {
9054                // Ignore entries which are not packages
9055                continue;
9056            }
9057            parallelPackageParser.submit(file, parseFlags);
9058            fileCount++;
9059        }
9060
9061        // Process results one by one
9062        for (; fileCount > 0; fileCount--) {
9063            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9064            Throwable throwable = parseResult.throwable;
9065            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9066
9067            if (throwable == null) {
9068                // Static shared libraries have synthetic package names
9069                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9070                    renameStaticSharedLibraryPackage(parseResult.pkg);
9071                }
9072                try {
9073                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9074                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9075                                currentTime, null);
9076                    }
9077                } catch (PackageManagerException e) {
9078                    errorCode = e.error;
9079                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9080                }
9081            } else if (throwable instanceof PackageParser.PackageParserException) {
9082                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9083                        throwable;
9084                errorCode = e.error;
9085                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9086            } else {
9087                throw new IllegalStateException("Unexpected exception occurred while parsing "
9088                        + parseResult.scanFile, throwable);
9089            }
9090
9091            // Delete invalid userdata apps
9092            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9093                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9094                logCriticalInfo(Log.WARN,
9095                        "Deleting invalid package at " + parseResult.scanFile);
9096                removeCodePathLI(parseResult.scanFile);
9097            }
9098        }
9099        parallelPackageParser.close();
9100    }
9101
9102    private static File getSettingsProblemFile() {
9103        File dataDir = Environment.getDataDirectory();
9104        File systemDir = new File(dataDir, "system");
9105        File fname = new File(systemDir, "uiderrors.txt");
9106        return fname;
9107    }
9108
9109    static void reportSettingsProblem(int priority, String msg) {
9110        logCriticalInfo(priority, msg);
9111    }
9112
9113    public static void logCriticalInfo(int priority, String msg) {
9114        Slog.println(priority, TAG, msg);
9115        EventLogTags.writePmCriticalInfo(msg);
9116        try {
9117            File fname = getSettingsProblemFile();
9118            FileOutputStream out = new FileOutputStream(fname, true);
9119            PrintWriter pw = new FastPrintWriter(out);
9120            SimpleDateFormat formatter = new SimpleDateFormat();
9121            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9122            pw.println(dateString + ": " + msg);
9123            pw.close();
9124            FileUtils.setPermissions(
9125                    fname.toString(),
9126                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9127                    -1, -1);
9128        } catch (java.io.IOException e) {
9129        }
9130    }
9131
9132    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9133        if (srcFile.isDirectory()) {
9134            final File baseFile = new File(pkg.baseCodePath);
9135            long maxModifiedTime = baseFile.lastModified();
9136            if (pkg.splitCodePaths != null) {
9137                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9138                    final File splitFile = new File(pkg.splitCodePaths[i]);
9139                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9140                }
9141            }
9142            return maxModifiedTime;
9143        }
9144        return srcFile.lastModified();
9145    }
9146
9147    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9148            final int policyFlags) throws PackageManagerException {
9149        // When upgrading from pre-N MR1, verify the package time stamp using the package
9150        // directory and not the APK file.
9151        final long lastModifiedTime = mIsPreNMR1Upgrade
9152                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9153        if (ps != null
9154                && ps.codePath.equals(srcFile)
9155                && ps.timeStamp == lastModifiedTime
9156                && !isCompatSignatureUpdateNeeded(pkg)
9157                && !isRecoverSignatureUpdateNeeded(pkg)) {
9158            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9159            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9160            ArraySet<PublicKey> signingKs;
9161            synchronized (mPackages) {
9162                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9163            }
9164            if (ps.signatures.mSignatures != null
9165                    && ps.signatures.mSignatures.length != 0
9166                    && signingKs != null) {
9167                // Optimization: reuse the existing cached certificates
9168                // if the package appears to be unchanged.
9169                pkg.mSignatures = ps.signatures.mSignatures;
9170                pkg.mSigningKeys = signingKs;
9171                return;
9172            }
9173
9174            Slog.w(TAG, "PackageSetting for " + ps.name
9175                    + " is missing signatures.  Collecting certs again to recover them.");
9176        } else {
9177            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9178        }
9179
9180        try {
9181            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9182            PackageParser.collectCertificates(pkg, policyFlags);
9183        } catch (PackageParserException e) {
9184            throw PackageManagerException.from(e);
9185        } finally {
9186            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9187        }
9188    }
9189
9190    /**
9191     *  Traces a package scan.
9192     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9193     */
9194    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9195            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9196        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9197        try {
9198            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9199        } finally {
9200            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9201        }
9202    }
9203
9204    /**
9205     *  Scans a package and returns the newly parsed package.
9206     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9207     */
9208    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9209            long currentTime, UserHandle user) throws PackageManagerException {
9210        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9211        PackageParser pp = new PackageParser();
9212        pp.setSeparateProcesses(mSeparateProcesses);
9213        pp.setOnlyCoreApps(mOnlyCore);
9214        pp.setDisplayMetrics(mMetrics);
9215        pp.setCallback(mPackageParserCallback);
9216
9217        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9218            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9219        }
9220
9221        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9222        final PackageParser.Package pkg;
9223        try {
9224            pkg = pp.parsePackage(scanFile, parseFlags);
9225        } catch (PackageParserException e) {
9226            throw PackageManagerException.from(e);
9227        } finally {
9228            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9229        }
9230
9231        // Static shared libraries have synthetic package names
9232        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9233            renameStaticSharedLibraryPackage(pkg);
9234        }
9235
9236        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9237    }
9238
9239    /**
9240     *  Scans a package and returns the newly parsed package.
9241     *  @throws PackageManagerException on a parse error.
9242     */
9243    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9244            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9245            throws PackageManagerException {
9246        // If the package has children and this is the first dive in the function
9247        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9248        // packages (parent and children) would be successfully scanned before the
9249        // actual scan since scanning mutates internal state and we want to atomically
9250        // install the package and its children.
9251        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9252            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9253                scanFlags |= SCAN_CHECK_ONLY;
9254            }
9255        } else {
9256            scanFlags &= ~SCAN_CHECK_ONLY;
9257        }
9258
9259        // Scan the parent
9260        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9261                scanFlags, currentTime, user);
9262
9263        // Scan the children
9264        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9265        for (int i = 0; i < childCount; i++) {
9266            PackageParser.Package childPackage = pkg.childPackages.get(i);
9267            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9268                    currentTime, user);
9269        }
9270
9271
9272        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9273            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9274        }
9275
9276        return scannedPkg;
9277    }
9278
9279    /**
9280     *  Scans a package and returns the newly parsed package.
9281     *  @throws PackageManagerException on a parse error.
9282     */
9283    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9284            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9285            throws PackageManagerException {
9286        PackageSetting ps = null;
9287        PackageSetting updatedPkg;
9288        // reader
9289        synchronized (mPackages) {
9290            // Look to see if we already know about this package.
9291            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9292            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9293                // This package has been renamed to its original name.  Let's
9294                // use that.
9295                ps = mSettings.getPackageLPr(oldName);
9296            }
9297            // If there was no original package, see one for the real package name.
9298            if (ps == null) {
9299                ps = mSettings.getPackageLPr(pkg.packageName);
9300            }
9301            // Check to see if this package could be hiding/updating a system
9302            // package.  Must look for it either under the original or real
9303            // package name depending on our state.
9304            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9305            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9306
9307            // If this is a package we don't know about on the system partition, we
9308            // may need to remove disabled child packages on the system partition
9309            // or may need to not add child packages if the parent apk is updated
9310            // on the data partition and no longer defines this child package.
9311            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9312                // If this is a parent package for an updated system app and this system
9313                // app got an OTA update which no longer defines some of the child packages
9314                // we have to prune them from the disabled system packages.
9315                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9316                if (disabledPs != null) {
9317                    final int scannedChildCount = (pkg.childPackages != null)
9318                            ? pkg.childPackages.size() : 0;
9319                    final int disabledChildCount = disabledPs.childPackageNames != null
9320                            ? disabledPs.childPackageNames.size() : 0;
9321                    for (int i = 0; i < disabledChildCount; i++) {
9322                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9323                        boolean disabledPackageAvailable = false;
9324                        for (int j = 0; j < scannedChildCount; j++) {
9325                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9326                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9327                                disabledPackageAvailable = true;
9328                                break;
9329                            }
9330                         }
9331                         if (!disabledPackageAvailable) {
9332                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9333                         }
9334                    }
9335                }
9336            }
9337        }
9338
9339        final boolean isUpdatedPkg = updatedPkg != null;
9340        final boolean isUpdatedSystemPkg = isUpdatedPkg
9341                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9342        boolean isUpdatedPkgBetter = false;
9343        // First check if this is a system package that may involve an update
9344        if (isUpdatedSystemPkg) {
9345            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9346            // it needs to drop FLAG_PRIVILEGED.
9347            if (locationIsPrivileged(scanFile)) {
9348                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9349            } else {
9350                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9351            }
9352            // If new package is not located in "/oem" (e.g. due to an OTA),
9353            // it needs to drop FLAG_OEM.
9354            if (locationIsOem(scanFile)) {
9355                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
9356            } else {
9357                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
9358            }
9359
9360            if (ps != null && !ps.codePath.equals(scanFile)) {
9361                // The path has changed from what was last scanned...  check the
9362                // version of the new path against what we have stored to determine
9363                // what to do.
9364                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9365                if (pkg.mVersionCode <= ps.versionCode) {
9366                    // The system package has been updated and the code path does not match
9367                    // Ignore entry. Skip it.
9368                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9369                            + " ignored: updated version " + ps.versionCode
9370                            + " better than this " + pkg.mVersionCode);
9371                    if (!updatedPkg.codePath.equals(scanFile)) {
9372                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9373                                + ps.name + " changing from " + updatedPkg.codePathString
9374                                + " to " + scanFile);
9375                        updatedPkg.codePath = scanFile;
9376                        updatedPkg.codePathString = scanFile.toString();
9377                        updatedPkg.resourcePath = scanFile;
9378                        updatedPkg.resourcePathString = scanFile.toString();
9379                    }
9380                    updatedPkg.pkg = pkg;
9381                    updatedPkg.versionCode = pkg.mVersionCode;
9382
9383                    // Update the disabled system child packages to point to the package too.
9384                    final int childCount = updatedPkg.childPackageNames != null
9385                            ? updatedPkg.childPackageNames.size() : 0;
9386                    for (int i = 0; i < childCount; i++) {
9387                        String childPackageName = updatedPkg.childPackageNames.get(i);
9388                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9389                                childPackageName);
9390                        if (updatedChildPkg != null) {
9391                            updatedChildPkg.pkg = pkg;
9392                            updatedChildPkg.versionCode = pkg.mVersionCode;
9393                        }
9394                    }
9395                } else {
9396                    // The current app on the system partition is better than
9397                    // what we have updated to on the data partition; switch
9398                    // back to the system partition version.
9399                    // At this point, its safely assumed that package installation for
9400                    // apps in system partition will go through. If not there won't be a working
9401                    // version of the app
9402                    // writer
9403                    synchronized (mPackages) {
9404                        // Just remove the loaded entries from package lists.
9405                        mPackages.remove(ps.name);
9406                    }
9407
9408                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9409                            + " reverting from " + ps.codePathString
9410                            + ": new version " + pkg.mVersionCode
9411                            + " better than installed " + ps.versionCode);
9412
9413                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9414                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9415                    synchronized (mInstallLock) {
9416                        args.cleanUpResourcesLI();
9417                    }
9418                    synchronized (mPackages) {
9419                        mSettings.enableSystemPackageLPw(ps.name);
9420                    }
9421                    isUpdatedPkgBetter = true;
9422                }
9423            }
9424        }
9425
9426        String resourcePath = null;
9427        String baseResourcePath = null;
9428        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9429            if (ps != null && ps.resourcePathString != null) {
9430                resourcePath = ps.resourcePathString;
9431                baseResourcePath = ps.resourcePathString;
9432            } else {
9433                // Should not happen at all. Just log an error.
9434                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9435            }
9436        } else {
9437            resourcePath = pkg.codePath;
9438            baseResourcePath = pkg.baseCodePath;
9439        }
9440
9441        // Set application objects path explicitly.
9442        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9443        pkg.setApplicationInfoCodePath(pkg.codePath);
9444        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9445        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9446        pkg.setApplicationInfoResourcePath(resourcePath);
9447        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9448        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9449
9450        // throw an exception if we have an update to a system application, but, it's not more
9451        // recent than the package we've already scanned
9452        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9453            // Set CPU Abis to application info.
9454            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9455                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9456                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9457            } else {
9458                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9459                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9460            }
9461
9462            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9463                    + scanFile + " ignored: updated version " + ps.versionCode
9464                    + " better than this " + pkg.mVersionCode);
9465        }
9466
9467        if (isUpdatedPkg) {
9468            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9469            // initially
9470            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9471
9472            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9473            // flag set initially
9474            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9475                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9476            }
9477
9478            // An updated OEM app will not have the PARSE_IS_OEM
9479            // flag set initially
9480            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9481                policyFlags |= PackageParser.PARSE_IS_OEM;
9482            }
9483        }
9484
9485        // Verify certificates against what was last scanned
9486        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9487
9488        /*
9489         * A new system app appeared, but we already had a non-system one of the
9490         * same name installed earlier.
9491         */
9492        boolean shouldHideSystemApp = false;
9493        if (!isUpdatedPkg && ps != null
9494                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9495            /*
9496             * Check to make sure the signatures match first. If they don't,
9497             * wipe the installed application and its data.
9498             */
9499            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9500                    != PackageManager.SIGNATURE_MATCH) {
9501                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9502                        + " signatures don't match existing userdata copy; removing");
9503                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9504                        "scanPackageInternalLI")) {
9505                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9506                }
9507                ps = null;
9508            } else {
9509                /*
9510                 * If the newly-added system app is an older version than the
9511                 * already installed version, hide it. It will be scanned later
9512                 * and re-added like an update.
9513                 */
9514                if (pkg.mVersionCode <= ps.versionCode) {
9515                    shouldHideSystemApp = true;
9516                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9517                            + " but new version " + pkg.mVersionCode + " better than installed "
9518                            + ps.versionCode + "; hiding system");
9519                } else {
9520                    /*
9521                     * The newly found system app is a newer version that the
9522                     * one previously installed. Simply remove the
9523                     * already-installed application and replace it with our own
9524                     * while keeping the application data.
9525                     */
9526                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9527                            + " reverting from " + ps.codePathString + ": new version "
9528                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9529                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9530                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9531                    synchronized (mInstallLock) {
9532                        args.cleanUpResourcesLI();
9533                    }
9534                }
9535            }
9536        }
9537
9538        // The apk is forward locked (not public) if its code and resources
9539        // are kept in different files. (except for app in either system or
9540        // vendor path).
9541        // TODO grab this value from PackageSettings
9542        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9543            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9544                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9545            }
9546        }
9547
9548        final int userId = ((user == null) ? 0 : user.getIdentifier());
9549        if (ps != null && ps.getInstantApp(userId)) {
9550            scanFlags |= SCAN_AS_INSTANT_APP;
9551        }
9552        if (ps != null && ps.getVirtulalPreload(userId)) {
9553            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9554        }
9555
9556        // Note that we invoke the following method only if we are about to unpack an application
9557        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9558                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9559
9560        /*
9561         * If the system app should be overridden by a previously installed
9562         * data, hide the system app now and let the /data/app scan pick it up
9563         * again.
9564         */
9565        if (shouldHideSystemApp) {
9566            synchronized (mPackages) {
9567                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9568            }
9569        }
9570
9571        return scannedPkg;
9572    }
9573
9574    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9575        // Derive the new package synthetic package name
9576        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9577                + pkg.staticSharedLibVersion);
9578    }
9579
9580    private static String fixProcessName(String defProcessName,
9581            String processName) {
9582        if (processName == null) {
9583            return defProcessName;
9584        }
9585        return processName;
9586    }
9587
9588    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9589            throws PackageManagerException {
9590        if (pkgSetting.signatures.mSignatures != null) {
9591            // Already existing package. Make sure signatures match
9592            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9593                    == PackageManager.SIGNATURE_MATCH;
9594            if (!match) {
9595                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9596                        == PackageManager.SIGNATURE_MATCH;
9597            }
9598            if (!match) {
9599                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9600                        == PackageManager.SIGNATURE_MATCH;
9601            }
9602            if (!match) {
9603                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9604                        + pkg.packageName + " signatures do not match the "
9605                        + "previously installed version; ignoring!");
9606            }
9607        }
9608
9609        // Check for shared user signatures
9610        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9611            // Already existing package. Make sure signatures match
9612            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9613                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9614            if (!match) {
9615                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9616                        == PackageManager.SIGNATURE_MATCH;
9617            }
9618            if (!match) {
9619                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9620                        == PackageManager.SIGNATURE_MATCH;
9621            }
9622            if (!match) {
9623                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9624                        "Package " + pkg.packageName
9625                        + " has no signatures that match those in shared user "
9626                        + pkgSetting.sharedUser.name + "; ignoring!");
9627            }
9628        }
9629    }
9630
9631    /**
9632     * Enforces that only the system UID or root's UID can call a method exposed
9633     * via Binder.
9634     *
9635     * @param message used as message if SecurityException is thrown
9636     * @throws SecurityException if the caller is not system or root
9637     */
9638    private static final void enforceSystemOrRoot(String message) {
9639        final int uid = Binder.getCallingUid();
9640        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9641            throw new SecurityException(message);
9642        }
9643    }
9644
9645    @Override
9646    public void performFstrimIfNeeded() {
9647        enforceSystemOrRoot("Only the system can request fstrim");
9648
9649        // Before everything else, see whether we need to fstrim.
9650        try {
9651            IStorageManager sm = PackageHelper.getStorageManager();
9652            if (sm != null) {
9653                boolean doTrim = false;
9654                final long interval = android.provider.Settings.Global.getLong(
9655                        mContext.getContentResolver(),
9656                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9657                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9658                if (interval > 0) {
9659                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9660                    if (timeSinceLast > interval) {
9661                        doTrim = true;
9662                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9663                                + "; running immediately");
9664                    }
9665                }
9666                if (doTrim) {
9667                    final boolean dexOptDialogShown;
9668                    synchronized (mPackages) {
9669                        dexOptDialogShown = mDexOptDialogShown;
9670                    }
9671                    if (!isFirstBoot() && dexOptDialogShown) {
9672                        try {
9673                            ActivityManager.getService().showBootMessage(
9674                                    mContext.getResources().getString(
9675                                            R.string.android_upgrading_fstrim), true);
9676                        } catch (RemoteException e) {
9677                        }
9678                    }
9679                    sm.runMaintenance();
9680                }
9681            } else {
9682                Slog.e(TAG, "storageManager service unavailable!");
9683            }
9684        } catch (RemoteException e) {
9685            // Can't happen; StorageManagerService is local
9686        }
9687    }
9688
9689    @Override
9690    public void updatePackagesIfNeeded() {
9691        enforceSystemOrRoot("Only the system can request package update");
9692
9693        // We need to re-extract after an OTA.
9694        boolean causeUpgrade = isUpgrade();
9695
9696        // First boot or factory reset.
9697        // Note: we also handle devices that are upgrading to N right now as if it is their
9698        //       first boot, as they do not have profile data.
9699        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9700
9701        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9702        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9703
9704        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9705            return;
9706        }
9707
9708        List<PackageParser.Package> pkgs;
9709        synchronized (mPackages) {
9710            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9711        }
9712
9713        final long startTime = System.nanoTime();
9714        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9715                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9716                    false /* bootComplete */);
9717
9718        final int elapsedTimeSeconds =
9719                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9720
9721        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9722        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9723        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9724        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9725        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9726    }
9727
9728    /*
9729     * Return the prebuilt profile path given a package base code path.
9730     */
9731    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9732        return pkg.baseCodePath + ".prof";
9733    }
9734
9735    /**
9736     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9737     * containing statistics about the invocation. The array consists of three elements,
9738     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9739     * and {@code numberOfPackagesFailed}.
9740     */
9741    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9742            String compilerFilter, boolean bootComplete) {
9743
9744        int numberOfPackagesVisited = 0;
9745        int numberOfPackagesOptimized = 0;
9746        int numberOfPackagesSkipped = 0;
9747        int numberOfPackagesFailed = 0;
9748        final int numberOfPackagesToDexopt = pkgs.size();
9749
9750        for (PackageParser.Package pkg : pkgs) {
9751            numberOfPackagesVisited++;
9752
9753            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9754                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9755                // that are already compiled.
9756                File profileFile = new File(getPrebuildProfilePath(pkg));
9757                // Copy profile if it exists.
9758                if (profileFile.exists()) {
9759                    try {
9760                        // We could also do this lazily before calling dexopt in
9761                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9762                        // is that we don't have a good way to say "do this only once".
9763                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9764                                pkg.applicationInfo.uid, pkg.packageName)) {
9765                            Log.e(TAG, "Installer failed to copy system profile!");
9766                        }
9767                    } catch (Exception e) {
9768                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9769                                e);
9770                    }
9771                }
9772            }
9773
9774            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9775                if (DEBUG_DEXOPT) {
9776                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9777                }
9778                numberOfPackagesSkipped++;
9779                continue;
9780            }
9781
9782            if (DEBUG_DEXOPT) {
9783                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9784                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9785            }
9786
9787            if (showDialog) {
9788                try {
9789                    ActivityManager.getService().showBootMessage(
9790                            mContext.getResources().getString(R.string.android_upgrading_apk,
9791                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9792                } catch (RemoteException e) {
9793                }
9794                synchronized (mPackages) {
9795                    mDexOptDialogShown = true;
9796                }
9797            }
9798
9799            // checkProfiles is false to avoid merging profiles during boot which
9800            // might interfere with background compilation (b/28612421).
9801            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9802            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9803            // trade-off worth doing to save boot time work.
9804            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9805            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9806                    pkg.packageName,
9807                    compilerFilter,
9808                    dexoptFlags));
9809
9810            switch (primaryDexOptStaus) {
9811                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9812                    numberOfPackagesOptimized++;
9813                    break;
9814                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9815                    numberOfPackagesSkipped++;
9816                    break;
9817                case PackageDexOptimizer.DEX_OPT_FAILED:
9818                    numberOfPackagesFailed++;
9819                    break;
9820                default:
9821                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9822                    break;
9823            }
9824        }
9825
9826        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9827                numberOfPackagesFailed };
9828    }
9829
9830    @Override
9831    public void notifyPackageUse(String packageName, int reason) {
9832        synchronized (mPackages) {
9833            final int callingUid = Binder.getCallingUid();
9834            final int callingUserId = UserHandle.getUserId(callingUid);
9835            if (getInstantAppPackageName(callingUid) != null) {
9836                if (!isCallerSameApp(packageName, callingUid)) {
9837                    return;
9838                }
9839            } else {
9840                if (isInstantApp(packageName, callingUserId)) {
9841                    return;
9842                }
9843            }
9844            notifyPackageUseLocked(packageName, reason);
9845        }
9846    }
9847
9848    private void notifyPackageUseLocked(String packageName, int reason) {
9849        final PackageParser.Package p = mPackages.get(packageName);
9850        if (p == null) {
9851            return;
9852        }
9853        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9854    }
9855
9856    @Override
9857    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9858            List<String> classPaths, String loaderIsa) {
9859        int userId = UserHandle.getCallingUserId();
9860        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9861        if (ai == null) {
9862            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9863                + loadingPackageName + ", user=" + userId);
9864            return;
9865        }
9866        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9867    }
9868
9869    @Override
9870    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9871            IDexModuleRegisterCallback callback) {
9872        int userId = UserHandle.getCallingUserId();
9873        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9874        DexManager.RegisterDexModuleResult result;
9875        if (ai == null) {
9876            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9877                     " calling user. package=" + packageName + ", user=" + userId);
9878            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9879        } else {
9880            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9881        }
9882
9883        if (callback != null) {
9884            mHandler.post(() -> {
9885                try {
9886                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9887                } catch (RemoteException e) {
9888                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9889                }
9890            });
9891        }
9892    }
9893
9894    /**
9895     * Ask the package manager to perform a dex-opt with the given compiler filter.
9896     *
9897     * Note: exposed only for the shell command to allow moving packages explicitly to a
9898     *       definite state.
9899     */
9900    @Override
9901    public boolean performDexOptMode(String packageName,
9902            boolean checkProfiles, String targetCompilerFilter, boolean force,
9903            boolean bootComplete, String splitName) {
9904        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9905                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9906                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9907        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9908                splitName, flags));
9909    }
9910
9911    /**
9912     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9913     * secondary dex files belonging to the given package.
9914     *
9915     * Note: exposed only for the shell command to allow moving packages explicitly to a
9916     *       definite state.
9917     */
9918    @Override
9919    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9920            boolean force) {
9921        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9922                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9923                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9924                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9925        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9926    }
9927
9928    /*package*/ boolean performDexOpt(DexoptOptions options) {
9929        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9930            return false;
9931        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9932            return false;
9933        }
9934
9935        if (options.isDexoptOnlySecondaryDex()) {
9936            return mDexManager.dexoptSecondaryDex(options);
9937        } else {
9938            int dexoptStatus = performDexOptWithStatus(options);
9939            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9940        }
9941    }
9942
9943    /**
9944     * Perform dexopt on the given package and return one of following result:
9945     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9946     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9947     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9948     */
9949    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9950        return performDexOptTraced(options);
9951    }
9952
9953    private int performDexOptTraced(DexoptOptions options) {
9954        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9955        try {
9956            return performDexOptInternal(options);
9957        } finally {
9958            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9959        }
9960    }
9961
9962    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9963    // if the package can now be considered up to date for the given filter.
9964    private int performDexOptInternal(DexoptOptions options) {
9965        PackageParser.Package p;
9966        synchronized (mPackages) {
9967            p = mPackages.get(options.getPackageName());
9968            if (p == null) {
9969                // Package could not be found. Report failure.
9970                return PackageDexOptimizer.DEX_OPT_FAILED;
9971            }
9972            mPackageUsage.maybeWriteAsync(mPackages);
9973            mCompilerStats.maybeWriteAsync();
9974        }
9975        long callingId = Binder.clearCallingIdentity();
9976        try {
9977            synchronized (mInstallLock) {
9978                return performDexOptInternalWithDependenciesLI(p, options);
9979            }
9980        } finally {
9981            Binder.restoreCallingIdentity(callingId);
9982        }
9983    }
9984
9985    public ArraySet<String> getOptimizablePackages() {
9986        ArraySet<String> pkgs = new ArraySet<String>();
9987        synchronized (mPackages) {
9988            for (PackageParser.Package p : mPackages.values()) {
9989                if (PackageDexOptimizer.canOptimizePackage(p)) {
9990                    pkgs.add(p.packageName);
9991                }
9992            }
9993        }
9994        return pkgs;
9995    }
9996
9997    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9998            DexoptOptions options) {
9999        // Select the dex optimizer based on the force parameter.
10000        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10001        //       allocate an object here.
10002        PackageDexOptimizer pdo = options.isForce()
10003                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10004                : mPackageDexOptimizer;
10005
10006        // Dexopt all dependencies first. Note: we ignore the return value and march on
10007        // on errors.
10008        // Note that we are going to call performDexOpt on those libraries as many times as
10009        // they are referenced in packages. When we do a batch of performDexOpt (for example
10010        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10011        // and the first package that uses the library will dexopt it. The
10012        // others will see that the compiled code for the library is up to date.
10013        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10014        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10015        if (!deps.isEmpty()) {
10016            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10017                    options.getCompilerFilter(), options.getSplitName(),
10018                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10019            for (PackageParser.Package depPackage : deps) {
10020                // TODO: Analyze and investigate if we (should) profile libraries.
10021                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10022                        getOrCreateCompilerPackageStats(depPackage),
10023                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10024            }
10025        }
10026        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10027                getOrCreateCompilerPackageStats(p),
10028                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10029    }
10030
10031    /**
10032     * Reconcile the information we have about the secondary dex files belonging to
10033     * {@code packagName} and the actual dex files. For all dex files that were
10034     * deleted, update the internal records and delete the generated oat files.
10035     */
10036    @Override
10037    public void reconcileSecondaryDexFiles(String packageName) {
10038        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10039            return;
10040        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10041            return;
10042        }
10043        mDexManager.reconcileSecondaryDexFiles(packageName);
10044    }
10045
10046    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10047    // a reference there.
10048    /*package*/ DexManager getDexManager() {
10049        return mDexManager;
10050    }
10051
10052    /**
10053     * Execute the background dexopt job immediately.
10054     */
10055    @Override
10056    public boolean runBackgroundDexoptJob() {
10057        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10058            return false;
10059        }
10060        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10061    }
10062
10063    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10064        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10065                || p.usesStaticLibraries != null) {
10066            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10067            Set<String> collectedNames = new HashSet<>();
10068            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10069
10070            retValue.remove(p);
10071
10072            return retValue;
10073        } else {
10074            return Collections.emptyList();
10075        }
10076    }
10077
10078    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10079            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10080        if (!collectedNames.contains(p.packageName)) {
10081            collectedNames.add(p.packageName);
10082            collected.add(p);
10083
10084            if (p.usesLibraries != null) {
10085                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10086                        null, collected, collectedNames);
10087            }
10088            if (p.usesOptionalLibraries != null) {
10089                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10090                        null, collected, collectedNames);
10091            }
10092            if (p.usesStaticLibraries != null) {
10093                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10094                        p.usesStaticLibrariesVersions, collected, collectedNames);
10095            }
10096        }
10097    }
10098
10099    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10100            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10101        final int libNameCount = libs.size();
10102        for (int i = 0; i < libNameCount; i++) {
10103            String libName = libs.get(i);
10104            int version = (versions != null && versions.length == libNameCount)
10105                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10106            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10107            if (libPkg != null) {
10108                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10109            }
10110        }
10111    }
10112
10113    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10114        synchronized (mPackages) {
10115            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10116            if (libEntry != null) {
10117                return mPackages.get(libEntry.apk);
10118            }
10119            return null;
10120        }
10121    }
10122
10123    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10124        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10125        if (versionedLib == null) {
10126            return null;
10127        }
10128        return versionedLib.get(version);
10129    }
10130
10131    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10132        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10133                pkg.staticSharedLibName);
10134        if (versionedLib == null) {
10135            return null;
10136        }
10137        int previousLibVersion = -1;
10138        final int versionCount = versionedLib.size();
10139        for (int i = 0; i < versionCount; i++) {
10140            final int libVersion = versionedLib.keyAt(i);
10141            if (libVersion < pkg.staticSharedLibVersion) {
10142                previousLibVersion = Math.max(previousLibVersion, libVersion);
10143            }
10144        }
10145        if (previousLibVersion >= 0) {
10146            return versionedLib.get(previousLibVersion);
10147        }
10148        return null;
10149    }
10150
10151    public void shutdown() {
10152        mPackageUsage.writeNow(mPackages);
10153        mCompilerStats.writeNow();
10154        mDexManager.writePackageDexUsageNow();
10155    }
10156
10157    @Override
10158    public void dumpProfiles(String packageName) {
10159        PackageParser.Package pkg;
10160        synchronized (mPackages) {
10161            pkg = mPackages.get(packageName);
10162            if (pkg == null) {
10163                throw new IllegalArgumentException("Unknown package: " + packageName);
10164            }
10165        }
10166        /* Only the shell, root, or the app user should be able to dump profiles. */
10167        int callingUid = Binder.getCallingUid();
10168        if (callingUid != Process.SHELL_UID &&
10169            callingUid != Process.ROOT_UID &&
10170            callingUid != pkg.applicationInfo.uid) {
10171            throw new SecurityException("dumpProfiles");
10172        }
10173
10174        synchronized (mInstallLock) {
10175            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10176            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10177            try {
10178                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10179                String codePaths = TextUtils.join(";", allCodePaths);
10180                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10181            } catch (InstallerException e) {
10182                Slog.w(TAG, "Failed to dump profiles", e);
10183            }
10184            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10185        }
10186    }
10187
10188    @Override
10189    public void forceDexOpt(String packageName) {
10190        enforceSystemOrRoot("forceDexOpt");
10191
10192        PackageParser.Package pkg;
10193        synchronized (mPackages) {
10194            pkg = mPackages.get(packageName);
10195            if (pkg == null) {
10196                throw new IllegalArgumentException("Unknown package: " + packageName);
10197            }
10198        }
10199
10200        synchronized (mInstallLock) {
10201            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10202
10203            // Whoever is calling forceDexOpt wants a compiled package.
10204            // Don't use profiles since that may cause compilation to be skipped.
10205            final int res = performDexOptInternalWithDependenciesLI(
10206                    pkg,
10207                    new DexoptOptions(packageName,
10208                            getDefaultCompilerFilter(),
10209                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10210
10211            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10212            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10213                throw new IllegalStateException("Failed to dexopt: " + res);
10214            }
10215        }
10216    }
10217
10218    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10219        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10220            Slog.w(TAG, "Unable to update from " + oldPkg.name
10221                    + " to " + newPkg.packageName
10222                    + ": old package not in system partition");
10223            return false;
10224        } else if (mPackages.get(oldPkg.name) != null) {
10225            Slog.w(TAG, "Unable to update from " + oldPkg.name
10226                    + " to " + newPkg.packageName
10227                    + ": old package still exists");
10228            return false;
10229        }
10230        return true;
10231    }
10232
10233    void removeCodePathLI(File codePath) {
10234        if (codePath.isDirectory()) {
10235            try {
10236                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10237            } catch (InstallerException e) {
10238                Slog.w(TAG, "Failed to remove code path", e);
10239            }
10240        } else {
10241            codePath.delete();
10242        }
10243    }
10244
10245    private int[] resolveUserIds(int userId) {
10246        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10247    }
10248
10249    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10250        if (pkg == null) {
10251            Slog.wtf(TAG, "Package was null!", new Throwable());
10252            return;
10253        }
10254        clearAppDataLeafLIF(pkg, userId, flags);
10255        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10256        for (int i = 0; i < childCount; i++) {
10257            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10258        }
10259    }
10260
10261    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10262        final PackageSetting ps;
10263        synchronized (mPackages) {
10264            ps = mSettings.mPackages.get(pkg.packageName);
10265        }
10266        for (int realUserId : resolveUserIds(userId)) {
10267            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10268            try {
10269                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10270                        ceDataInode);
10271            } catch (InstallerException e) {
10272                Slog.w(TAG, String.valueOf(e));
10273            }
10274        }
10275    }
10276
10277    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10278        if (pkg == null) {
10279            Slog.wtf(TAG, "Package was null!", new Throwable());
10280            return;
10281        }
10282        destroyAppDataLeafLIF(pkg, userId, flags);
10283        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10284        for (int i = 0; i < childCount; i++) {
10285            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10286        }
10287    }
10288
10289    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10290        final PackageSetting ps;
10291        synchronized (mPackages) {
10292            ps = mSettings.mPackages.get(pkg.packageName);
10293        }
10294        for (int realUserId : resolveUserIds(userId)) {
10295            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10296            try {
10297                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10298                        ceDataInode);
10299            } catch (InstallerException e) {
10300                Slog.w(TAG, String.valueOf(e));
10301            }
10302            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10303        }
10304    }
10305
10306    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10307        if (pkg == null) {
10308            Slog.wtf(TAG, "Package was null!", new Throwable());
10309            return;
10310        }
10311        destroyAppProfilesLeafLIF(pkg);
10312        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10313        for (int i = 0; i < childCount; i++) {
10314            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10315        }
10316    }
10317
10318    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10319        try {
10320            mInstaller.destroyAppProfiles(pkg.packageName);
10321        } catch (InstallerException e) {
10322            Slog.w(TAG, String.valueOf(e));
10323        }
10324    }
10325
10326    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10327        if (pkg == null) {
10328            Slog.wtf(TAG, "Package was null!", new Throwable());
10329            return;
10330        }
10331        clearAppProfilesLeafLIF(pkg);
10332        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10333        for (int i = 0; i < childCount; i++) {
10334            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10335        }
10336    }
10337
10338    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10339        try {
10340            mInstaller.clearAppProfiles(pkg.packageName);
10341        } catch (InstallerException e) {
10342            Slog.w(TAG, String.valueOf(e));
10343        }
10344    }
10345
10346    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10347            long lastUpdateTime) {
10348        // Set parent install/update time
10349        PackageSetting ps = (PackageSetting) pkg.mExtras;
10350        if (ps != null) {
10351            ps.firstInstallTime = firstInstallTime;
10352            ps.lastUpdateTime = lastUpdateTime;
10353        }
10354        // Set children install/update time
10355        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10356        for (int i = 0; i < childCount; i++) {
10357            PackageParser.Package childPkg = pkg.childPackages.get(i);
10358            ps = (PackageSetting) childPkg.mExtras;
10359            if (ps != null) {
10360                ps.firstInstallTime = firstInstallTime;
10361                ps.lastUpdateTime = lastUpdateTime;
10362            }
10363        }
10364    }
10365
10366    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10367            PackageParser.Package changingLib) {
10368        if (file.path != null) {
10369            usesLibraryFiles.add(file.path);
10370            return;
10371        }
10372        PackageParser.Package p = mPackages.get(file.apk);
10373        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10374            // If we are doing this while in the middle of updating a library apk,
10375            // then we need to make sure to use that new apk for determining the
10376            // dependencies here.  (We haven't yet finished committing the new apk
10377            // to the package manager state.)
10378            if (p == null || p.packageName.equals(changingLib.packageName)) {
10379                p = changingLib;
10380            }
10381        }
10382        if (p != null) {
10383            usesLibraryFiles.addAll(p.getAllCodePaths());
10384            if (p.usesLibraryFiles != null) {
10385                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10386            }
10387        }
10388    }
10389
10390    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10391            PackageParser.Package changingLib) throws PackageManagerException {
10392        if (pkg == null) {
10393            return;
10394        }
10395        ArraySet<String> usesLibraryFiles = null;
10396        if (pkg.usesLibraries != null) {
10397            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10398                    null, null, pkg.packageName, changingLib, true,
10399                    pkg.applicationInfo.targetSdkVersion, null);
10400        }
10401        if (pkg.usesStaticLibraries != null) {
10402            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10403                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10404                    pkg.packageName, changingLib, true,
10405                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10406        }
10407        if (pkg.usesOptionalLibraries != null) {
10408            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10409                    null, null, pkg.packageName, changingLib, false,
10410                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10411        }
10412        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10413            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10414        } else {
10415            pkg.usesLibraryFiles = null;
10416        }
10417    }
10418
10419    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10420            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10421            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10422            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10423            throws PackageManagerException {
10424        final int libCount = requestedLibraries.size();
10425        for (int i = 0; i < libCount; i++) {
10426            final String libName = requestedLibraries.get(i);
10427            final int libVersion = requiredVersions != null ? requiredVersions[i]
10428                    : SharedLibraryInfo.VERSION_UNDEFINED;
10429            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10430            if (libEntry == null) {
10431                if (required) {
10432                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10433                            "Package " + packageName + " requires unavailable shared library "
10434                                    + libName + "; failing!");
10435                } else if (DEBUG_SHARED_LIBRARIES) {
10436                    Slog.i(TAG, "Package " + packageName
10437                            + " desires unavailable shared library "
10438                            + libName + "; ignoring!");
10439                }
10440            } else {
10441                if (requiredVersions != null && requiredCertDigests != null) {
10442                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10443                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10444                            "Package " + packageName + " requires unavailable static shared"
10445                                    + " library " + libName + " version "
10446                                    + libEntry.info.getVersion() + "; failing!");
10447                    }
10448
10449                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10450                    if (libPkg == null) {
10451                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10452                                "Package " + packageName + " requires unavailable static shared"
10453                                        + " library; failing!");
10454                    }
10455
10456                    final String[] expectedCertDigests = requiredCertDigests[i];
10457                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10458                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10459                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10460                            : PackageUtils.computeSignaturesSha256Digests(
10461                                    new Signature[]{libPkg.mSignatures[0]});
10462
10463                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10464                    // target O we don't parse the "additional-certificate" tags similarly
10465                    // how we only consider all certs only for apps targeting O (see above).
10466                    // Therefore, the size check is safe to make.
10467                    if (expectedCertDigests.length != libCertDigests.length) {
10468                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10469                                "Package " + packageName + " requires differently signed" +
10470                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10471                    }
10472
10473                    // Use a predictable order as signature order may vary
10474                    Arrays.sort(libCertDigests);
10475                    Arrays.sort(expectedCertDigests);
10476
10477                    final int certCount = libCertDigests.length;
10478                    for (int j = 0; j < certCount; j++) {
10479                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10480                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10481                                    "Package " + packageName + " requires differently signed" +
10482                                            " static shared library; failing!");
10483                        }
10484                    }
10485                }
10486
10487                if (outUsedLibraries == null) {
10488                    outUsedLibraries = new ArraySet<>();
10489                }
10490                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10491            }
10492        }
10493        return outUsedLibraries;
10494    }
10495
10496    private static boolean hasString(List<String> list, List<String> which) {
10497        if (list == null) {
10498            return false;
10499        }
10500        for (int i=list.size()-1; i>=0; i--) {
10501            for (int j=which.size()-1; j>=0; j--) {
10502                if (which.get(j).equals(list.get(i))) {
10503                    return true;
10504                }
10505            }
10506        }
10507        return false;
10508    }
10509
10510    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10511            PackageParser.Package changingPkg) {
10512        ArrayList<PackageParser.Package> res = null;
10513        for (PackageParser.Package pkg : mPackages.values()) {
10514            if (changingPkg != null
10515                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10516                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10517                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10518                            changingPkg.staticSharedLibName)) {
10519                return null;
10520            }
10521            if (res == null) {
10522                res = new ArrayList<>();
10523            }
10524            res.add(pkg);
10525            try {
10526                updateSharedLibrariesLPr(pkg, changingPkg);
10527            } catch (PackageManagerException e) {
10528                // If a system app update or an app and a required lib missing we
10529                // delete the package and for updated system apps keep the data as
10530                // it is better for the user to reinstall than to be in an limbo
10531                // state. Also libs disappearing under an app should never happen
10532                // - just in case.
10533                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10534                    final int flags = pkg.isUpdatedSystemApp()
10535                            ? PackageManager.DELETE_KEEP_DATA : 0;
10536                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10537                            flags , null, true, null);
10538                }
10539                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10540            }
10541        }
10542        return res;
10543    }
10544
10545    /**
10546     * Derive the value of the {@code cpuAbiOverride} based on the provided
10547     * value and an optional stored value from the package settings.
10548     */
10549    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10550        String cpuAbiOverride = null;
10551
10552        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10553            cpuAbiOverride = null;
10554        } else if (abiOverride != null) {
10555            cpuAbiOverride = abiOverride;
10556        } else if (settings != null) {
10557            cpuAbiOverride = settings.cpuAbiOverrideString;
10558        }
10559
10560        return cpuAbiOverride;
10561    }
10562
10563    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10564            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10565                    throws PackageManagerException {
10566        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10567        // If the package has children and this is the first dive in the function
10568        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10569        // whether all packages (parent and children) would be successfully scanned
10570        // before the actual scan since scanning mutates internal state and we want
10571        // to atomically install the package and its children.
10572        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10573            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10574                scanFlags |= SCAN_CHECK_ONLY;
10575            }
10576        } else {
10577            scanFlags &= ~SCAN_CHECK_ONLY;
10578        }
10579
10580        final PackageParser.Package scannedPkg;
10581        try {
10582            // Scan the parent
10583            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10584            // Scan the children
10585            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10586            for (int i = 0; i < childCount; i++) {
10587                PackageParser.Package childPkg = pkg.childPackages.get(i);
10588                scanPackageLI(childPkg, policyFlags,
10589                        scanFlags, currentTime, user);
10590            }
10591        } finally {
10592            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10593        }
10594
10595        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10596            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10597        }
10598
10599        return scannedPkg;
10600    }
10601
10602    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10603            int scanFlags, long currentTime, @Nullable UserHandle user)
10604                    throws PackageManagerException {
10605        boolean success = false;
10606        try {
10607            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10608                    currentTime, user);
10609            success = true;
10610            return res;
10611        } finally {
10612            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10613                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10614                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10615                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10616                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10617            }
10618        }
10619    }
10620
10621    /**
10622     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10623     */
10624    private static boolean apkHasCode(String fileName) {
10625        StrictJarFile jarFile = null;
10626        try {
10627            jarFile = new StrictJarFile(fileName,
10628                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10629            return jarFile.findEntry("classes.dex") != null;
10630        } catch (IOException ignore) {
10631        } finally {
10632            try {
10633                if (jarFile != null) {
10634                    jarFile.close();
10635                }
10636            } catch (IOException ignore) {}
10637        }
10638        return false;
10639    }
10640
10641    /**
10642     * Enforces code policy for the package. This ensures that if an APK has
10643     * declared hasCode="true" in its manifest that the APK actually contains
10644     * code.
10645     *
10646     * @throws PackageManagerException If bytecode could not be found when it should exist
10647     */
10648    private static void assertCodePolicy(PackageParser.Package pkg)
10649            throws PackageManagerException {
10650        final boolean shouldHaveCode =
10651                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10652        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10653            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10654                    "Package " + pkg.baseCodePath + " code is missing");
10655        }
10656
10657        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10658            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10659                final boolean splitShouldHaveCode =
10660                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10661                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10662                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10663                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10664                }
10665            }
10666        }
10667    }
10668
10669    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10670            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10671                    throws PackageManagerException {
10672        if (DEBUG_PACKAGE_SCANNING) {
10673            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10674                Log.d(TAG, "Scanning package " + pkg.packageName);
10675        }
10676
10677        applyPolicy(pkg, policyFlags);
10678
10679        assertPackageIsValid(pkg, policyFlags, scanFlags);
10680
10681        if (Build.IS_DEBUGGABLE &&
10682                pkg.isPrivilegedApp() &&
10683                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10684            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10685        }
10686
10687        // Initialize package source and resource directories
10688        final File scanFile = new File(pkg.codePath);
10689        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10690        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10691
10692        SharedUserSetting suid = null;
10693        PackageSetting pkgSetting = null;
10694
10695        // Getting the package setting may have a side-effect, so if we
10696        // are only checking if scan would succeed, stash a copy of the
10697        // old setting to restore at the end.
10698        PackageSetting nonMutatedPs = null;
10699
10700        // We keep references to the derived CPU Abis from settings in oder to reuse
10701        // them in the case where we're not upgrading or booting for the first time.
10702        String primaryCpuAbiFromSettings = null;
10703        String secondaryCpuAbiFromSettings = null;
10704
10705        // writer
10706        synchronized (mPackages) {
10707            if (pkg.mSharedUserId != null) {
10708                // SIDE EFFECTS; may potentially allocate a new shared user
10709                suid = mSettings.getSharedUserLPw(
10710                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10711                if (DEBUG_PACKAGE_SCANNING) {
10712                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10713                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10714                                + "): packages=" + suid.packages);
10715                }
10716            }
10717
10718            // Check if we are renaming from an original package name.
10719            PackageSetting origPackage = null;
10720            String realName = null;
10721            if (pkg.mOriginalPackages != null) {
10722                // This package may need to be renamed to a previously
10723                // installed name.  Let's check on that...
10724                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10725                if (pkg.mOriginalPackages.contains(renamed)) {
10726                    // This package had originally been installed as the
10727                    // original name, and we have already taken care of
10728                    // transitioning to the new one.  Just update the new
10729                    // one to continue using the old name.
10730                    realName = pkg.mRealPackage;
10731                    if (!pkg.packageName.equals(renamed)) {
10732                        // Callers into this function may have already taken
10733                        // care of renaming the package; only do it here if
10734                        // it is not already done.
10735                        pkg.setPackageName(renamed);
10736                    }
10737                } else {
10738                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10739                        if ((origPackage = mSettings.getPackageLPr(
10740                                pkg.mOriginalPackages.get(i))) != null) {
10741                            // We do have the package already installed under its
10742                            // original name...  should we use it?
10743                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10744                                // New package is not compatible with original.
10745                                origPackage = null;
10746                                continue;
10747                            } else if (origPackage.sharedUser != null) {
10748                                // Make sure uid is compatible between packages.
10749                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10750                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10751                                            + " to " + pkg.packageName + ": old uid "
10752                                            + origPackage.sharedUser.name
10753                                            + " differs from " + pkg.mSharedUserId);
10754                                    origPackage = null;
10755                                    continue;
10756                                }
10757                                // TODO: Add case when shared user id is added [b/28144775]
10758                            } else {
10759                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10760                                        + pkg.packageName + " to old name " + origPackage.name);
10761                            }
10762                            break;
10763                        }
10764                    }
10765                }
10766            }
10767
10768            if (mTransferedPackages.contains(pkg.packageName)) {
10769                Slog.w(TAG, "Package " + pkg.packageName
10770                        + " was transferred to another, but its .apk remains");
10771            }
10772
10773            // See comments in nonMutatedPs declaration
10774            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10775                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10776                if (foundPs != null) {
10777                    nonMutatedPs = new PackageSetting(foundPs);
10778                }
10779            }
10780
10781            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10782                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10783                if (foundPs != null) {
10784                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10785                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10786                }
10787            }
10788
10789            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10790            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10791                PackageManagerService.reportSettingsProblem(Log.WARN,
10792                        "Package " + pkg.packageName + " shared user changed from "
10793                                + (pkgSetting.sharedUser != null
10794                                        ? pkgSetting.sharedUser.name : "<nothing>")
10795                                + " to "
10796                                + (suid != null ? suid.name : "<nothing>")
10797                                + "; replacing with new");
10798                pkgSetting = null;
10799            }
10800            final PackageSetting oldPkgSetting =
10801                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10802            final PackageSetting disabledPkgSetting =
10803                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10804
10805            String[] usesStaticLibraries = null;
10806            if (pkg.usesStaticLibraries != null) {
10807                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10808                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10809            }
10810
10811            if (pkgSetting == null) {
10812                final String parentPackageName = (pkg.parentPackage != null)
10813                        ? pkg.parentPackage.packageName : null;
10814                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10815                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10816                // REMOVE SharedUserSetting from method; update in a separate call
10817                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10818                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10819                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10820                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10821                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10822                        true /*allowInstall*/, instantApp, virtualPreload,
10823                        parentPackageName, pkg.getChildPackageNames(),
10824                        UserManagerService.getInstance(), usesStaticLibraries,
10825                        pkg.usesStaticLibrariesVersions);
10826                // SIDE EFFECTS; updates system state; move elsewhere
10827                if (origPackage != null) {
10828                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10829                }
10830                mSettings.addUserToSettingLPw(pkgSetting);
10831            } else {
10832                // REMOVE SharedUserSetting from method; update in a separate call.
10833                //
10834                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10835                // secondaryCpuAbi are not known at this point so we always update them
10836                // to null here, only to reset them at a later point.
10837                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10838                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10839                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10840                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10841                        UserManagerService.getInstance(), usesStaticLibraries,
10842                        pkg.usesStaticLibrariesVersions);
10843            }
10844            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10845            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10846
10847            // SIDE EFFECTS; modifies system state; move elsewhere
10848            if (pkgSetting.origPackage != null) {
10849                // If we are first transitioning from an original package,
10850                // fix up the new package's name now.  We need to do this after
10851                // looking up the package under its new name, so getPackageLP
10852                // can take care of fiddling things correctly.
10853                pkg.setPackageName(origPackage.name);
10854
10855                // File a report about this.
10856                String msg = "New package " + pkgSetting.realName
10857                        + " renamed to replace old package " + pkgSetting.name;
10858                reportSettingsProblem(Log.WARN, msg);
10859
10860                // Make a note of it.
10861                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10862                    mTransferedPackages.add(origPackage.name);
10863                }
10864
10865                // No longer need to retain this.
10866                pkgSetting.origPackage = null;
10867            }
10868
10869            // SIDE EFFECTS; modifies system state; move elsewhere
10870            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10871                // Make a note of it.
10872                mTransferedPackages.add(pkg.packageName);
10873            }
10874
10875            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10876                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10877            }
10878
10879            if ((scanFlags & SCAN_BOOTING) == 0
10880                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10881                // Check all shared libraries and map to their actual file path.
10882                // We only do this here for apps not on a system dir, because those
10883                // are the only ones that can fail an install due to this.  We
10884                // will take care of the system apps by updating all of their
10885                // library paths after the scan is done. Also during the initial
10886                // scan don't update any libs as we do this wholesale after all
10887                // apps are scanned to avoid dependency based scanning.
10888                updateSharedLibrariesLPr(pkg, null);
10889            }
10890
10891            if (mFoundPolicyFile) {
10892                SELinuxMMAC.assignSeInfoValue(pkg);
10893            }
10894            pkg.applicationInfo.uid = pkgSetting.appId;
10895            pkg.mExtras = pkgSetting;
10896
10897
10898            // Static shared libs have same package with different versions where
10899            // we internally use a synthetic package name to allow multiple versions
10900            // of the same package, therefore we need to compare signatures against
10901            // the package setting for the latest library version.
10902            PackageSetting signatureCheckPs = pkgSetting;
10903            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10904                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10905                if (libraryEntry != null) {
10906                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10907                }
10908            }
10909
10910            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10911                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10912                    // We just determined the app is signed correctly, so bring
10913                    // over the latest parsed certs.
10914                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10915                } else {
10916                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10917                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10918                                "Package " + pkg.packageName + " upgrade keys do not match the "
10919                                + "previously installed version");
10920                    } else {
10921                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10922                        String msg = "System package " + pkg.packageName
10923                                + " signature changed; retaining data.";
10924                        reportSettingsProblem(Log.WARN, msg);
10925                    }
10926                }
10927            } else {
10928                try {
10929                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10930                    verifySignaturesLP(signatureCheckPs, pkg);
10931                    // We just determined the app is signed correctly, so bring
10932                    // over the latest parsed certs.
10933                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10934                } catch (PackageManagerException e) {
10935                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10936                        throw e;
10937                    }
10938                    // The signature has changed, but this package is in the system
10939                    // image...  let's recover!
10940                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10941                    // However...  if this package is part of a shared user, but it
10942                    // doesn't match the signature of the shared user, let's fail.
10943                    // What this means is that you can't change the signatures
10944                    // associated with an overall shared user, which doesn't seem all
10945                    // that unreasonable.
10946                    if (signatureCheckPs.sharedUser != null) {
10947                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10948                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10949                            throw new PackageManagerException(
10950                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10951                                    "Signature mismatch for shared user: "
10952                                            + pkgSetting.sharedUser);
10953                        }
10954                    }
10955                    // File a report about this.
10956                    String msg = "System package " + pkg.packageName
10957                            + " signature changed; retaining data.";
10958                    reportSettingsProblem(Log.WARN, msg);
10959                }
10960            }
10961
10962            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10963                // This package wants to adopt ownership of permissions from
10964                // another package.
10965                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10966                    final String origName = pkg.mAdoptPermissions.get(i);
10967                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10968                    if (orig != null) {
10969                        if (verifyPackageUpdateLPr(orig, pkg)) {
10970                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10971                                    + pkg.packageName);
10972                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10973                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10974                        }
10975                    }
10976                }
10977            }
10978        }
10979
10980        pkg.applicationInfo.processName = fixProcessName(
10981                pkg.applicationInfo.packageName,
10982                pkg.applicationInfo.processName);
10983
10984        if (pkg != mPlatformPackage) {
10985            // Get all of our default paths setup
10986            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10987        }
10988
10989        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10990
10991        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10992            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10993                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10994                final boolean extractNativeLibs = !pkg.isLibrary();
10995                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10996                        mAppLib32InstallDir);
10997                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10998
10999                // Some system apps still use directory structure for native libraries
11000                // in which case we might end up not detecting abi solely based on apk
11001                // structure. Try to detect abi based on directory structure.
11002                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11003                        pkg.applicationInfo.primaryCpuAbi == null) {
11004                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11005                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11006                }
11007            } else {
11008                // This is not a first boot or an upgrade, don't bother deriving the
11009                // ABI during the scan. Instead, trust the value that was stored in the
11010                // package setting.
11011                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11012                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11013
11014                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11015
11016                if (DEBUG_ABI_SELECTION) {
11017                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11018                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11019                        pkg.applicationInfo.secondaryCpuAbi);
11020                }
11021            }
11022        } else {
11023            if ((scanFlags & SCAN_MOVE) != 0) {
11024                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11025                // but we already have this packages package info in the PackageSetting. We just
11026                // use that and derive the native library path based on the new codepath.
11027                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11028                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11029            }
11030
11031            // Set native library paths again. For moves, the path will be updated based on the
11032            // ABIs we've determined above. For non-moves, the path will be updated based on the
11033            // ABIs we determined during compilation, but the path will depend on the final
11034            // package path (after the rename away from the stage path).
11035            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11036        }
11037
11038        // This is a special case for the "system" package, where the ABI is
11039        // dictated by the zygote configuration (and init.rc). We should keep track
11040        // of this ABI so that we can deal with "normal" applications that run under
11041        // the same UID correctly.
11042        if (mPlatformPackage == pkg) {
11043            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11044                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11045        }
11046
11047        // If there's a mismatch between the abi-override in the package setting
11048        // and the abiOverride specified for the install. Warn about this because we
11049        // would've already compiled the app without taking the package setting into
11050        // account.
11051        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11052            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11053                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11054                        " for package " + pkg.packageName);
11055            }
11056        }
11057
11058        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11059        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11060        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11061
11062        // Copy the derived override back to the parsed package, so that we can
11063        // update the package settings accordingly.
11064        pkg.cpuAbiOverride = cpuAbiOverride;
11065
11066        if (DEBUG_ABI_SELECTION) {
11067            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11068                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11069                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11070        }
11071
11072        // Push the derived path down into PackageSettings so we know what to
11073        // clean up at uninstall time.
11074        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11075
11076        if (DEBUG_ABI_SELECTION) {
11077            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11078                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11079                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11080        }
11081
11082        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11083        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11084            // We don't do this here during boot because we can do it all
11085            // at once after scanning all existing packages.
11086            //
11087            // We also do this *before* we perform dexopt on this package, so that
11088            // we can avoid redundant dexopts, and also to make sure we've got the
11089            // code and package path correct.
11090            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11091        }
11092
11093        if (mFactoryTest && pkg.requestedPermissions.contains(
11094                android.Manifest.permission.FACTORY_TEST)) {
11095            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11096        }
11097
11098        if (isSystemApp(pkg)) {
11099            pkgSetting.isOrphaned = true;
11100        }
11101
11102        // Take care of first install / last update times.
11103        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11104        if (currentTime != 0) {
11105            if (pkgSetting.firstInstallTime == 0) {
11106                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11107            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11108                pkgSetting.lastUpdateTime = currentTime;
11109            }
11110        } else if (pkgSetting.firstInstallTime == 0) {
11111            // We need *something*.  Take time time stamp of the file.
11112            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11113        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11114            if (scanFileTime != pkgSetting.timeStamp) {
11115                // A package on the system image has changed; consider this
11116                // to be an update.
11117                pkgSetting.lastUpdateTime = scanFileTime;
11118            }
11119        }
11120        pkgSetting.setTimeStamp(scanFileTime);
11121
11122        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11123            if (nonMutatedPs != null) {
11124                synchronized (mPackages) {
11125                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11126                }
11127            }
11128        } else {
11129            final int userId = user == null ? 0 : user.getIdentifier();
11130            // Modify state for the given package setting
11131            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11132                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11133            if (pkgSetting.getInstantApp(userId)) {
11134                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11135            }
11136        }
11137        return pkg;
11138    }
11139
11140    /**
11141     * Applies policy to the parsed package based upon the given policy flags.
11142     * Ensures the package is in a good state.
11143     * <p>
11144     * Implementation detail: This method must NOT have any side effect. It would
11145     * ideally be static, but, it requires locks to read system state.
11146     */
11147    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11148        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11149            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11150            if (pkg.applicationInfo.isDirectBootAware()) {
11151                // we're direct boot aware; set for all components
11152                for (PackageParser.Service s : pkg.services) {
11153                    s.info.encryptionAware = s.info.directBootAware = true;
11154                }
11155                for (PackageParser.Provider p : pkg.providers) {
11156                    p.info.encryptionAware = p.info.directBootAware = true;
11157                }
11158                for (PackageParser.Activity a : pkg.activities) {
11159                    a.info.encryptionAware = a.info.directBootAware = true;
11160                }
11161                for (PackageParser.Activity r : pkg.receivers) {
11162                    r.info.encryptionAware = r.info.directBootAware = true;
11163                }
11164            }
11165            if (compressedFileExists(pkg.codePath)) {
11166                pkg.isStub = true;
11167            }
11168        } else {
11169            // Only allow system apps to be flagged as core apps.
11170            pkg.coreApp = false;
11171            // clear flags not applicable to regular apps
11172            pkg.applicationInfo.privateFlags &=
11173                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11174            pkg.applicationInfo.privateFlags &=
11175                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11176        }
11177        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11178
11179        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11180            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11181        }
11182
11183        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
11184            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
11185        }
11186
11187        if (!isSystemApp(pkg)) {
11188            // Only system apps can use these features.
11189            pkg.mOriginalPackages = null;
11190            pkg.mRealPackage = null;
11191            pkg.mAdoptPermissions = null;
11192        }
11193    }
11194
11195    /**
11196     * Asserts the parsed package is valid according to the given policy. If the
11197     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11198     * <p>
11199     * Implementation detail: This method must NOT have any side effects. It would
11200     * ideally be static, but, it requires locks to read system state.
11201     *
11202     * @throws PackageManagerException If the package fails any of the validation checks
11203     */
11204    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11205            throws PackageManagerException {
11206        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11207            assertCodePolicy(pkg);
11208        }
11209
11210        if (pkg.applicationInfo.getCodePath() == null ||
11211                pkg.applicationInfo.getResourcePath() == null) {
11212            // Bail out. The resource and code paths haven't been set.
11213            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11214                    "Code and resource paths haven't been set correctly");
11215        }
11216
11217        // Make sure we're not adding any bogus keyset info
11218        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11219        ksms.assertScannedPackageValid(pkg);
11220
11221        synchronized (mPackages) {
11222            // The special "android" package can only be defined once
11223            if (pkg.packageName.equals("android")) {
11224                if (mAndroidApplication != null) {
11225                    Slog.w(TAG, "*************************************************");
11226                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11227                    Slog.w(TAG, " codePath=" + pkg.codePath);
11228                    Slog.w(TAG, "*************************************************");
11229                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11230                            "Core android package being redefined.  Skipping.");
11231                }
11232            }
11233
11234            // A package name must be unique; don't allow duplicates
11235            if (mPackages.containsKey(pkg.packageName)) {
11236                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11237                        "Application package " + pkg.packageName
11238                        + " already installed.  Skipping duplicate.");
11239            }
11240
11241            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11242                // Static libs have a synthetic package name containing the version
11243                // but we still want the base name to be unique.
11244                if (mPackages.containsKey(pkg.manifestPackageName)) {
11245                    throw new PackageManagerException(
11246                            "Duplicate static shared lib provider package");
11247                }
11248
11249                // Static shared libraries should have at least O target SDK
11250                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11251                    throw new PackageManagerException(
11252                            "Packages declaring static-shared libs must target O SDK or higher");
11253                }
11254
11255                // Package declaring static a shared lib cannot be instant apps
11256                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11257                    throw new PackageManagerException(
11258                            "Packages declaring static-shared libs cannot be instant apps");
11259                }
11260
11261                // Package declaring static a shared lib cannot be renamed since the package
11262                // name is synthetic and apps can't code around package manager internals.
11263                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11264                    throw new PackageManagerException(
11265                            "Packages declaring static-shared libs cannot be renamed");
11266                }
11267
11268                // Package declaring static a shared lib cannot declare child packages
11269                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11270                    throw new PackageManagerException(
11271                            "Packages declaring static-shared libs cannot have child packages");
11272                }
11273
11274                // Package declaring static a shared lib cannot declare dynamic libs
11275                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11276                    throw new PackageManagerException(
11277                            "Packages declaring static-shared libs cannot declare dynamic libs");
11278                }
11279
11280                // Package declaring static a shared lib cannot declare shared users
11281                if (pkg.mSharedUserId != null) {
11282                    throw new PackageManagerException(
11283                            "Packages declaring static-shared libs cannot declare shared users");
11284                }
11285
11286                // Static shared libs cannot declare activities
11287                if (!pkg.activities.isEmpty()) {
11288                    throw new PackageManagerException(
11289                            "Static shared libs cannot declare activities");
11290                }
11291
11292                // Static shared libs cannot declare services
11293                if (!pkg.services.isEmpty()) {
11294                    throw new PackageManagerException(
11295                            "Static shared libs cannot declare services");
11296                }
11297
11298                // Static shared libs cannot declare providers
11299                if (!pkg.providers.isEmpty()) {
11300                    throw new PackageManagerException(
11301                            "Static shared libs cannot declare content providers");
11302                }
11303
11304                // Static shared libs cannot declare receivers
11305                if (!pkg.receivers.isEmpty()) {
11306                    throw new PackageManagerException(
11307                            "Static shared libs cannot declare broadcast receivers");
11308                }
11309
11310                // Static shared libs cannot declare permission groups
11311                if (!pkg.permissionGroups.isEmpty()) {
11312                    throw new PackageManagerException(
11313                            "Static shared libs cannot declare permission groups");
11314                }
11315
11316                // Static shared libs cannot declare permissions
11317                if (!pkg.permissions.isEmpty()) {
11318                    throw new PackageManagerException(
11319                            "Static shared libs cannot declare permissions");
11320                }
11321
11322                // Static shared libs cannot declare protected broadcasts
11323                if (pkg.protectedBroadcasts != null) {
11324                    throw new PackageManagerException(
11325                            "Static shared libs cannot declare protected broadcasts");
11326                }
11327
11328                // Static shared libs cannot be overlay targets
11329                if (pkg.mOverlayTarget != null) {
11330                    throw new PackageManagerException(
11331                            "Static shared libs cannot be overlay targets");
11332                }
11333
11334                // The version codes must be ordered as lib versions
11335                int minVersionCode = Integer.MIN_VALUE;
11336                int maxVersionCode = Integer.MAX_VALUE;
11337
11338                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11339                        pkg.staticSharedLibName);
11340                if (versionedLib != null) {
11341                    final int versionCount = versionedLib.size();
11342                    for (int i = 0; i < versionCount; i++) {
11343                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11344                        final int libVersionCode = libInfo.getDeclaringPackage()
11345                                .getVersionCode();
11346                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11347                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11348                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11349                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11350                        } else {
11351                            minVersionCode = maxVersionCode = libVersionCode;
11352                            break;
11353                        }
11354                    }
11355                }
11356                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11357                    throw new PackageManagerException("Static shared"
11358                            + " lib version codes must be ordered as lib versions");
11359                }
11360            }
11361
11362            // Only privileged apps and updated privileged apps can add child packages.
11363            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11364                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11365                    throw new PackageManagerException("Only privileged apps can add child "
11366                            + "packages. Ignoring package " + pkg.packageName);
11367                }
11368                final int childCount = pkg.childPackages.size();
11369                for (int i = 0; i < childCount; i++) {
11370                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11371                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11372                            childPkg.packageName)) {
11373                        throw new PackageManagerException("Can't override child of "
11374                                + "another disabled app. Ignoring package " + pkg.packageName);
11375                    }
11376                }
11377            }
11378
11379            // If we're only installing presumed-existing packages, require that the
11380            // scanned APK is both already known and at the path previously established
11381            // for it.  Previously unknown packages we pick up normally, but if we have an
11382            // a priori expectation about this package's install presence, enforce it.
11383            // With a singular exception for new system packages. When an OTA contains
11384            // a new system package, we allow the codepath to change from a system location
11385            // to the user-installed location. If we don't allow this change, any newer,
11386            // user-installed version of the application will be ignored.
11387            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11388                if (mExpectingBetter.containsKey(pkg.packageName)) {
11389                    logCriticalInfo(Log.WARN,
11390                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11391                } else {
11392                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11393                    if (known != null) {
11394                        if (DEBUG_PACKAGE_SCANNING) {
11395                            Log.d(TAG, "Examining " + pkg.codePath
11396                                    + " and requiring known paths " + known.codePathString
11397                                    + " & " + known.resourcePathString);
11398                        }
11399                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11400                                || !pkg.applicationInfo.getResourcePath().equals(
11401                                        known.resourcePathString)) {
11402                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11403                                    "Application package " + pkg.packageName
11404                                    + " found at " + pkg.applicationInfo.getCodePath()
11405                                    + " but expected at " + known.codePathString
11406                                    + "; ignoring.");
11407                        }
11408                    } else {
11409                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11410                                "Application package " + pkg.packageName
11411                                + " not found; ignoring.");
11412                    }
11413                }
11414            }
11415
11416            // Verify that this new package doesn't have any content providers
11417            // that conflict with existing packages.  Only do this if the
11418            // package isn't already installed, since we don't want to break
11419            // things that are installed.
11420            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11421                final int N = pkg.providers.size();
11422                int i;
11423                for (i=0; i<N; i++) {
11424                    PackageParser.Provider p = pkg.providers.get(i);
11425                    if (p.info.authority != null) {
11426                        String names[] = p.info.authority.split(";");
11427                        for (int j = 0; j < names.length; j++) {
11428                            if (mProvidersByAuthority.containsKey(names[j])) {
11429                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11430                                final String otherPackageName =
11431                                        ((other != null && other.getComponentName() != null) ?
11432                                                other.getComponentName().getPackageName() : "?");
11433                                throw new PackageManagerException(
11434                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11435                                        "Can't install because provider name " + names[j]
11436                                                + " (in package " + pkg.applicationInfo.packageName
11437                                                + ") is already used by " + otherPackageName);
11438                            }
11439                        }
11440                    }
11441                }
11442            }
11443        }
11444    }
11445
11446    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11447            int type, String declaringPackageName, int declaringVersionCode) {
11448        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11449        if (versionedLib == null) {
11450            versionedLib = new SparseArray<>();
11451            mSharedLibraries.put(name, versionedLib);
11452            if (type == SharedLibraryInfo.TYPE_STATIC) {
11453                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11454            }
11455        } else if (versionedLib.indexOfKey(version) >= 0) {
11456            return false;
11457        }
11458        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11459                version, type, declaringPackageName, declaringVersionCode);
11460        versionedLib.put(version, libEntry);
11461        return true;
11462    }
11463
11464    private boolean removeSharedLibraryLPw(String name, int version) {
11465        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11466        if (versionedLib == null) {
11467            return false;
11468        }
11469        final int libIdx = versionedLib.indexOfKey(version);
11470        if (libIdx < 0) {
11471            return false;
11472        }
11473        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11474        versionedLib.remove(version);
11475        if (versionedLib.size() <= 0) {
11476            mSharedLibraries.remove(name);
11477            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11478                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11479                        .getPackageName());
11480            }
11481        }
11482        return true;
11483    }
11484
11485    /**
11486     * Adds a scanned package to the system. When this method is finished, the package will
11487     * be available for query, resolution, etc...
11488     */
11489    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11490            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11491        final String pkgName = pkg.packageName;
11492        if (mCustomResolverComponentName != null &&
11493                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11494            setUpCustomResolverActivity(pkg);
11495        }
11496
11497        if (pkg.packageName.equals("android")) {
11498            synchronized (mPackages) {
11499                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11500                    // Set up information for our fall-back user intent resolution activity.
11501                    mPlatformPackage = pkg;
11502                    pkg.mVersionCode = mSdkVersion;
11503                    mAndroidApplication = pkg.applicationInfo;
11504                    if (!mResolverReplaced) {
11505                        mResolveActivity.applicationInfo = mAndroidApplication;
11506                        mResolveActivity.name = ResolverActivity.class.getName();
11507                        mResolveActivity.packageName = mAndroidApplication.packageName;
11508                        mResolveActivity.processName = "system:ui";
11509                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11510                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11511                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11512                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11513                        mResolveActivity.exported = true;
11514                        mResolveActivity.enabled = true;
11515                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11516                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11517                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11518                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11519                                | ActivityInfo.CONFIG_ORIENTATION
11520                                | ActivityInfo.CONFIG_KEYBOARD
11521                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11522                        mResolveInfo.activityInfo = mResolveActivity;
11523                        mResolveInfo.priority = 0;
11524                        mResolveInfo.preferredOrder = 0;
11525                        mResolveInfo.match = 0;
11526                        mResolveComponentName = new ComponentName(
11527                                mAndroidApplication.packageName, mResolveActivity.name);
11528                    }
11529                }
11530            }
11531        }
11532
11533        ArrayList<PackageParser.Package> clientLibPkgs = null;
11534        // writer
11535        synchronized (mPackages) {
11536            boolean hasStaticSharedLibs = false;
11537
11538            // Any app can add new static shared libraries
11539            if (pkg.staticSharedLibName != null) {
11540                // Static shared libs don't allow renaming as they have synthetic package
11541                // names to allow install of multiple versions, so use name from manifest.
11542                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11543                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11544                        pkg.manifestPackageName, pkg.mVersionCode)) {
11545                    hasStaticSharedLibs = true;
11546                } else {
11547                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11548                                + pkg.staticSharedLibName + " already exists; skipping");
11549                }
11550                // Static shared libs cannot be updated once installed since they
11551                // use synthetic package name which includes the version code, so
11552                // not need to update other packages's shared lib dependencies.
11553            }
11554
11555            if (!hasStaticSharedLibs
11556                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11557                // Only system apps can add new dynamic shared libraries.
11558                if (pkg.libraryNames != null) {
11559                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11560                        String name = pkg.libraryNames.get(i);
11561                        boolean allowed = false;
11562                        if (pkg.isUpdatedSystemApp()) {
11563                            // New library entries can only be added through the
11564                            // system image.  This is important to get rid of a lot
11565                            // of nasty edge cases: for example if we allowed a non-
11566                            // system update of the app to add a library, then uninstalling
11567                            // the update would make the library go away, and assumptions
11568                            // we made such as through app install filtering would now
11569                            // have allowed apps on the device which aren't compatible
11570                            // with it.  Better to just have the restriction here, be
11571                            // conservative, and create many fewer cases that can negatively
11572                            // impact the user experience.
11573                            final PackageSetting sysPs = mSettings
11574                                    .getDisabledSystemPkgLPr(pkg.packageName);
11575                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11576                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11577                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11578                                        allowed = true;
11579                                        break;
11580                                    }
11581                                }
11582                            }
11583                        } else {
11584                            allowed = true;
11585                        }
11586                        if (allowed) {
11587                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11588                                    SharedLibraryInfo.VERSION_UNDEFINED,
11589                                    SharedLibraryInfo.TYPE_DYNAMIC,
11590                                    pkg.packageName, pkg.mVersionCode)) {
11591                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11592                                        + name + " already exists; skipping");
11593                            }
11594                        } else {
11595                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11596                                    + name + " that is not declared on system image; skipping");
11597                        }
11598                    }
11599
11600                    if ((scanFlags & SCAN_BOOTING) == 0) {
11601                        // If we are not booting, we need to update any applications
11602                        // that are clients of our shared library.  If we are booting,
11603                        // this will all be done once the scan is complete.
11604                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11605                    }
11606                }
11607            }
11608        }
11609
11610        if ((scanFlags & SCAN_BOOTING) != 0) {
11611            // No apps can run during boot scan, so they don't need to be frozen
11612        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11613            // Caller asked to not kill app, so it's probably not frozen
11614        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11615            // Caller asked us to ignore frozen check for some reason; they
11616            // probably didn't know the package name
11617        } else {
11618            // We're doing major surgery on this package, so it better be frozen
11619            // right now to keep it from launching
11620            checkPackageFrozen(pkgName);
11621        }
11622
11623        // Also need to kill any apps that are dependent on the library.
11624        if (clientLibPkgs != null) {
11625            for (int i=0; i<clientLibPkgs.size(); i++) {
11626                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11627                killApplication(clientPkg.applicationInfo.packageName,
11628                        clientPkg.applicationInfo.uid, "update lib");
11629            }
11630        }
11631
11632        // writer
11633        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11634
11635        synchronized (mPackages) {
11636            // We don't expect installation to fail beyond this point
11637
11638            // Add the new setting to mSettings
11639            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11640            // Add the new setting to mPackages
11641            mPackages.put(pkg.applicationInfo.packageName, pkg);
11642            // Make sure we don't accidentally delete its data.
11643            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11644            while (iter.hasNext()) {
11645                PackageCleanItem item = iter.next();
11646                if (pkgName.equals(item.packageName)) {
11647                    iter.remove();
11648                }
11649            }
11650
11651            // Add the package's KeySets to the global KeySetManagerService
11652            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11653            ksms.addScannedPackageLPw(pkg);
11654
11655            int N = pkg.providers.size();
11656            StringBuilder r = null;
11657            int i;
11658            for (i=0; i<N; i++) {
11659                PackageParser.Provider p = pkg.providers.get(i);
11660                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11661                        p.info.processName);
11662                mProviders.addProvider(p);
11663                p.syncable = p.info.isSyncable;
11664                if (p.info.authority != null) {
11665                    String names[] = p.info.authority.split(";");
11666                    p.info.authority = null;
11667                    for (int j = 0; j < names.length; j++) {
11668                        if (j == 1 && p.syncable) {
11669                            // We only want the first authority for a provider to possibly be
11670                            // syncable, so if we already added this provider using a different
11671                            // authority clear the syncable flag. We copy the provider before
11672                            // changing it because the mProviders object contains a reference
11673                            // to a provider that we don't want to change.
11674                            // Only do this for the second authority since the resulting provider
11675                            // object can be the same for all future authorities for this provider.
11676                            p = new PackageParser.Provider(p);
11677                            p.syncable = false;
11678                        }
11679                        if (!mProvidersByAuthority.containsKey(names[j])) {
11680                            mProvidersByAuthority.put(names[j], p);
11681                            if (p.info.authority == null) {
11682                                p.info.authority = names[j];
11683                            } else {
11684                                p.info.authority = p.info.authority + ";" + names[j];
11685                            }
11686                            if (DEBUG_PACKAGE_SCANNING) {
11687                                if (chatty)
11688                                    Log.d(TAG, "Registered content provider: " + names[j]
11689                                            + ", className = " + p.info.name + ", isSyncable = "
11690                                            + p.info.isSyncable);
11691                            }
11692                        } else {
11693                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11694                            Slog.w(TAG, "Skipping provider name " + names[j] +
11695                                    " (in package " + pkg.applicationInfo.packageName +
11696                                    "): name already used by "
11697                                    + ((other != null && other.getComponentName() != null)
11698                                            ? other.getComponentName().getPackageName() : "?"));
11699                        }
11700                    }
11701                }
11702                if (chatty) {
11703                    if (r == null) {
11704                        r = new StringBuilder(256);
11705                    } else {
11706                        r.append(' ');
11707                    }
11708                    r.append(p.info.name);
11709                }
11710            }
11711            if (r != null) {
11712                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11713            }
11714
11715            N = pkg.services.size();
11716            r = null;
11717            for (i=0; i<N; i++) {
11718                PackageParser.Service s = pkg.services.get(i);
11719                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11720                        s.info.processName);
11721                mServices.addService(s);
11722                if (chatty) {
11723                    if (r == null) {
11724                        r = new StringBuilder(256);
11725                    } else {
11726                        r.append(' ');
11727                    }
11728                    r.append(s.info.name);
11729                }
11730            }
11731            if (r != null) {
11732                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11733            }
11734
11735            N = pkg.receivers.size();
11736            r = null;
11737            for (i=0; i<N; i++) {
11738                PackageParser.Activity a = pkg.receivers.get(i);
11739                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11740                        a.info.processName);
11741                mReceivers.addActivity(a, "receiver");
11742                if (chatty) {
11743                    if (r == null) {
11744                        r = new StringBuilder(256);
11745                    } else {
11746                        r.append(' ');
11747                    }
11748                    r.append(a.info.name);
11749                }
11750            }
11751            if (r != null) {
11752                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11753            }
11754
11755            N = pkg.activities.size();
11756            r = null;
11757            for (i=0; i<N; i++) {
11758                PackageParser.Activity a = pkg.activities.get(i);
11759                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11760                        a.info.processName);
11761                mActivities.addActivity(a, "activity");
11762                if (chatty) {
11763                    if (r == null) {
11764                        r = new StringBuilder(256);
11765                    } else {
11766                        r.append(' ');
11767                    }
11768                    r.append(a.info.name);
11769                }
11770            }
11771            if (r != null) {
11772                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11773            }
11774
11775            N = pkg.permissionGroups.size();
11776            r = null;
11777            for (i=0; i<N; i++) {
11778                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11779                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11780                final String curPackageName = cur == null ? null : cur.info.packageName;
11781                // Dont allow ephemeral apps to define new permission groups.
11782                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11783                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11784                            + pg.info.packageName
11785                            + " ignored: instant apps cannot define new permission groups.");
11786                    continue;
11787                }
11788                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11789                if (cur == null || isPackageUpdate) {
11790                    mPermissionGroups.put(pg.info.name, pg);
11791                    if (chatty) {
11792                        if (r == null) {
11793                            r = new StringBuilder(256);
11794                        } else {
11795                            r.append(' ');
11796                        }
11797                        if (isPackageUpdate) {
11798                            r.append("UPD:");
11799                        }
11800                        r.append(pg.info.name);
11801                    }
11802                } else {
11803                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11804                            + pg.info.packageName + " ignored: original from "
11805                            + cur.info.packageName);
11806                    if (chatty) {
11807                        if (r == null) {
11808                            r = new StringBuilder(256);
11809                        } else {
11810                            r.append(' ');
11811                        }
11812                        r.append("DUP:");
11813                        r.append(pg.info.name);
11814                    }
11815                }
11816            }
11817            if (r != null) {
11818                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11819            }
11820
11821            N = pkg.permissions.size();
11822            r = null;
11823            for (i=0; i<N; i++) {
11824                PackageParser.Permission p = pkg.permissions.get(i);
11825
11826                // Dont allow ephemeral apps to define new permissions.
11827                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11828                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11829                            + p.info.packageName
11830                            + " ignored: instant apps cannot define new permissions.");
11831                    continue;
11832                }
11833
11834                // Assume by default that we did not install this permission into the system.
11835                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11836
11837                // Now that permission groups have a special meaning, we ignore permission
11838                // groups for legacy apps to prevent unexpected behavior. In particular,
11839                // permissions for one app being granted to someone just because they happen
11840                // to be in a group defined by another app (before this had no implications).
11841                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11842                    p.group = mPermissionGroups.get(p.info.group);
11843                    // Warn for a permission in an unknown group.
11844                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11845                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11846                                + p.info.packageName + " in an unknown group " + p.info.group);
11847                    }
11848                }
11849
11850                ArrayMap<String, BasePermission> permissionMap =
11851                        p.tree ? mSettings.mPermissionTrees
11852                                : mSettings.mPermissions;
11853                BasePermission bp = permissionMap.get(p.info.name);
11854
11855                // Allow system apps to redefine non-system permissions
11856                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11857                    final boolean currentOwnerIsSystem = (bp.perm != null
11858                            && isSystemApp(bp.perm.owner));
11859                    if (isSystemApp(p.owner)) {
11860                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11861                            // It's a built-in permission and no owner, take ownership now
11862                            bp.packageSetting = pkgSetting;
11863                            bp.perm = p;
11864                            bp.uid = pkg.applicationInfo.uid;
11865                            bp.sourcePackage = p.info.packageName;
11866                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11867                        } else if (!currentOwnerIsSystem) {
11868                            String msg = "New decl " + p.owner + " of permission  "
11869                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11870                            reportSettingsProblem(Log.WARN, msg);
11871                            bp = null;
11872                        }
11873                    }
11874                }
11875
11876                if (bp == null) {
11877                    bp = new BasePermission(p.info.name, p.info.packageName,
11878                            BasePermission.TYPE_NORMAL);
11879                    permissionMap.put(p.info.name, bp);
11880                }
11881
11882                if (bp.perm == null) {
11883                    if (bp.sourcePackage == null
11884                            || bp.sourcePackage.equals(p.info.packageName)) {
11885                        BasePermission tree = findPermissionTreeLP(p.info.name);
11886                        if (tree == null
11887                                || tree.sourcePackage.equals(p.info.packageName)) {
11888                            bp.packageSetting = pkgSetting;
11889                            bp.perm = p;
11890                            bp.uid = pkg.applicationInfo.uid;
11891                            bp.sourcePackage = p.info.packageName;
11892                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11893                            if (chatty) {
11894                                if (r == null) {
11895                                    r = new StringBuilder(256);
11896                                } else {
11897                                    r.append(' ');
11898                                }
11899                                r.append(p.info.name);
11900                            }
11901                        } else {
11902                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11903                                    + p.info.packageName + " ignored: base tree "
11904                                    + tree.name + " is from package "
11905                                    + tree.sourcePackage);
11906                        }
11907                    } else {
11908                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11909                                + p.info.packageName + " ignored: original from "
11910                                + bp.sourcePackage);
11911                    }
11912                } else if (chatty) {
11913                    if (r == null) {
11914                        r = new StringBuilder(256);
11915                    } else {
11916                        r.append(' ');
11917                    }
11918                    r.append("DUP:");
11919                    r.append(p.info.name);
11920                }
11921                if (bp.perm == p) {
11922                    bp.protectionLevel = p.info.protectionLevel;
11923                }
11924            }
11925
11926            if (r != null) {
11927                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11928            }
11929
11930            N = pkg.instrumentation.size();
11931            r = null;
11932            for (i=0; i<N; i++) {
11933                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11934                a.info.packageName = pkg.applicationInfo.packageName;
11935                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11936                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11937                a.info.splitNames = pkg.splitNames;
11938                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11939                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11940                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11941                a.info.dataDir = pkg.applicationInfo.dataDir;
11942                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11943                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11944                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11945                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11946                mInstrumentation.put(a.getComponentName(), a);
11947                if (chatty) {
11948                    if (r == null) {
11949                        r = new StringBuilder(256);
11950                    } else {
11951                        r.append(' ');
11952                    }
11953                    r.append(a.info.name);
11954                }
11955            }
11956            if (r != null) {
11957                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11958            }
11959
11960            if (pkg.protectedBroadcasts != null) {
11961                N = pkg.protectedBroadcasts.size();
11962                synchronized (mProtectedBroadcasts) {
11963                    for (i = 0; i < N; i++) {
11964                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11965                    }
11966                }
11967            }
11968        }
11969
11970        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11971    }
11972
11973    /**
11974     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11975     * is derived purely on the basis of the contents of {@code scanFile} and
11976     * {@code cpuAbiOverride}.
11977     *
11978     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11979     */
11980    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11981                                 String cpuAbiOverride, boolean extractLibs,
11982                                 File appLib32InstallDir)
11983            throws PackageManagerException {
11984        // Give ourselves some initial paths; we'll come back for another
11985        // pass once we've determined ABI below.
11986        setNativeLibraryPaths(pkg, appLib32InstallDir);
11987
11988        // We would never need to extract libs for forward-locked and external packages,
11989        // since the container service will do it for us. We shouldn't attempt to
11990        // extract libs from system app when it was not updated.
11991        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11992                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11993            extractLibs = false;
11994        }
11995
11996        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11997        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11998
11999        NativeLibraryHelper.Handle handle = null;
12000        try {
12001            handle = NativeLibraryHelper.Handle.create(pkg);
12002            // TODO(multiArch): This can be null for apps that didn't go through the
12003            // usual installation process. We can calculate it again, like we
12004            // do during install time.
12005            //
12006            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12007            // unnecessary.
12008            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12009
12010            // Null out the abis so that they can be recalculated.
12011            pkg.applicationInfo.primaryCpuAbi = null;
12012            pkg.applicationInfo.secondaryCpuAbi = null;
12013            if (isMultiArch(pkg.applicationInfo)) {
12014                // Warn if we've set an abiOverride for multi-lib packages..
12015                // By definition, we need to copy both 32 and 64 bit libraries for
12016                // such packages.
12017                if (pkg.cpuAbiOverride != null
12018                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12019                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12020                }
12021
12022                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12023                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12024                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12025                    if (extractLibs) {
12026                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12027                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12028                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12029                                useIsaSpecificSubdirs);
12030                    } else {
12031                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12032                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12033                    }
12034                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12035                }
12036
12037                // Shared library native code should be in the APK zip aligned
12038                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12039                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12040                            "Shared library native lib extraction not supported");
12041                }
12042
12043                maybeThrowExceptionForMultiArchCopy(
12044                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12045
12046                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12047                    if (extractLibs) {
12048                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12049                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12050                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12051                                useIsaSpecificSubdirs);
12052                    } else {
12053                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12054                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12055                    }
12056                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12057                }
12058
12059                maybeThrowExceptionForMultiArchCopy(
12060                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12061
12062                if (abi64 >= 0) {
12063                    // Shared library native libs should be in the APK zip aligned
12064                    if (extractLibs && pkg.isLibrary()) {
12065                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12066                                "Shared library native lib extraction not supported");
12067                    }
12068                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12069                }
12070
12071                if (abi32 >= 0) {
12072                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12073                    if (abi64 >= 0) {
12074                        if (pkg.use32bitAbi) {
12075                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12076                            pkg.applicationInfo.primaryCpuAbi = abi;
12077                        } else {
12078                            pkg.applicationInfo.secondaryCpuAbi = abi;
12079                        }
12080                    } else {
12081                        pkg.applicationInfo.primaryCpuAbi = abi;
12082                    }
12083                }
12084            } else {
12085                String[] abiList = (cpuAbiOverride != null) ?
12086                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12087
12088                // Enable gross and lame hacks for apps that are built with old
12089                // SDK tools. We must scan their APKs for renderscript bitcode and
12090                // not launch them if it's present. Don't bother checking on devices
12091                // that don't have 64 bit support.
12092                boolean needsRenderScriptOverride = false;
12093                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12094                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12095                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12096                    needsRenderScriptOverride = true;
12097                }
12098
12099                final int copyRet;
12100                if (extractLibs) {
12101                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12102                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12103                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12104                } else {
12105                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12106                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12107                }
12108                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12109
12110                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12111                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12112                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12113                }
12114
12115                if (copyRet >= 0) {
12116                    // Shared libraries that have native libs must be multi-architecture
12117                    if (pkg.isLibrary()) {
12118                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12119                                "Shared library with native libs must be multiarch");
12120                    }
12121                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12122                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12123                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12124                } else if (needsRenderScriptOverride) {
12125                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12126                }
12127            }
12128        } catch (IOException ioe) {
12129            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12130        } finally {
12131            IoUtils.closeQuietly(handle);
12132        }
12133
12134        // Now that we've calculated the ABIs and determined if it's an internal app,
12135        // we will go ahead and populate the nativeLibraryPath.
12136        setNativeLibraryPaths(pkg, appLib32InstallDir);
12137    }
12138
12139    /**
12140     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12141     * i.e, so that all packages can be run inside a single process if required.
12142     *
12143     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12144     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12145     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12146     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12147     * updating a package that belongs to a shared user.
12148     *
12149     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12150     * adds unnecessary complexity.
12151     */
12152    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12153            PackageParser.Package scannedPackage) {
12154        String requiredInstructionSet = null;
12155        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12156            requiredInstructionSet = VMRuntime.getInstructionSet(
12157                     scannedPackage.applicationInfo.primaryCpuAbi);
12158        }
12159
12160        PackageSetting requirer = null;
12161        for (PackageSetting ps : packagesForUser) {
12162            // If packagesForUser contains scannedPackage, we skip it. This will happen
12163            // when scannedPackage is an update of an existing package. Without this check,
12164            // we will never be able to change the ABI of any package belonging to a shared
12165            // user, even if it's compatible with other packages.
12166            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12167                if (ps.primaryCpuAbiString == null) {
12168                    continue;
12169                }
12170
12171                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12172                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12173                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12174                    // this but there's not much we can do.
12175                    String errorMessage = "Instruction set mismatch, "
12176                            + ((requirer == null) ? "[caller]" : requirer)
12177                            + " requires " + requiredInstructionSet + " whereas " + ps
12178                            + " requires " + instructionSet;
12179                    Slog.w(TAG, errorMessage);
12180                }
12181
12182                if (requiredInstructionSet == null) {
12183                    requiredInstructionSet = instructionSet;
12184                    requirer = ps;
12185                }
12186            }
12187        }
12188
12189        if (requiredInstructionSet != null) {
12190            String adjustedAbi;
12191            if (requirer != null) {
12192                // requirer != null implies that either scannedPackage was null or that scannedPackage
12193                // did not require an ABI, in which case we have to adjust scannedPackage to match
12194                // the ABI of the set (which is the same as requirer's ABI)
12195                adjustedAbi = requirer.primaryCpuAbiString;
12196                if (scannedPackage != null) {
12197                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12198                }
12199            } else {
12200                // requirer == null implies that we're updating all ABIs in the set to
12201                // match scannedPackage.
12202                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12203            }
12204
12205            for (PackageSetting ps : packagesForUser) {
12206                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12207                    if (ps.primaryCpuAbiString != null) {
12208                        continue;
12209                    }
12210
12211                    ps.primaryCpuAbiString = adjustedAbi;
12212                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12213                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12214                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12215                        if (DEBUG_ABI_SELECTION) {
12216                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12217                                    + " (requirer="
12218                                    + (requirer != null ? requirer.pkg : "null")
12219                                    + ", scannedPackage="
12220                                    + (scannedPackage != null ? scannedPackage : "null")
12221                                    + ")");
12222                        }
12223                        try {
12224                            mInstaller.rmdex(ps.codePathString,
12225                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12226                        } catch (InstallerException ignored) {
12227                        }
12228                    }
12229                }
12230            }
12231        }
12232    }
12233
12234    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12235        synchronized (mPackages) {
12236            mResolverReplaced = true;
12237            // Set up information for custom user intent resolution activity.
12238            mResolveActivity.applicationInfo = pkg.applicationInfo;
12239            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12240            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12241            mResolveActivity.processName = pkg.applicationInfo.packageName;
12242            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12243            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12244                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12245            mResolveActivity.theme = 0;
12246            mResolveActivity.exported = true;
12247            mResolveActivity.enabled = true;
12248            mResolveInfo.activityInfo = mResolveActivity;
12249            mResolveInfo.priority = 0;
12250            mResolveInfo.preferredOrder = 0;
12251            mResolveInfo.match = 0;
12252            mResolveComponentName = mCustomResolverComponentName;
12253            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12254                    mResolveComponentName);
12255        }
12256    }
12257
12258    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12259        if (installerActivity == null) {
12260            if (DEBUG_EPHEMERAL) {
12261                Slog.d(TAG, "Clear ephemeral installer activity");
12262            }
12263            mInstantAppInstallerActivity = null;
12264            return;
12265        }
12266
12267        if (DEBUG_EPHEMERAL) {
12268            Slog.d(TAG, "Set ephemeral installer activity: "
12269                    + installerActivity.getComponentName());
12270        }
12271        // Set up information for ephemeral installer activity
12272        mInstantAppInstallerActivity = installerActivity;
12273        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12274                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12275        mInstantAppInstallerActivity.exported = true;
12276        mInstantAppInstallerActivity.enabled = true;
12277        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12278        mInstantAppInstallerInfo.priority = 0;
12279        mInstantAppInstallerInfo.preferredOrder = 1;
12280        mInstantAppInstallerInfo.isDefault = true;
12281        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12282                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12283    }
12284
12285    private static String calculateBundledApkRoot(final String codePathString) {
12286        final File codePath = new File(codePathString);
12287        final File codeRoot;
12288        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12289            codeRoot = Environment.getRootDirectory();
12290        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12291            codeRoot = Environment.getOemDirectory();
12292        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12293            codeRoot = Environment.getVendorDirectory();
12294        } else {
12295            // Unrecognized code path; take its top real segment as the apk root:
12296            // e.g. /something/app/blah.apk => /something
12297            try {
12298                File f = codePath.getCanonicalFile();
12299                File parent = f.getParentFile();    // non-null because codePath is a file
12300                File tmp;
12301                while ((tmp = parent.getParentFile()) != null) {
12302                    f = parent;
12303                    parent = tmp;
12304                }
12305                codeRoot = f;
12306                Slog.w(TAG, "Unrecognized code path "
12307                        + codePath + " - using " + codeRoot);
12308            } catch (IOException e) {
12309                // Can't canonicalize the code path -- shenanigans?
12310                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12311                return Environment.getRootDirectory().getPath();
12312            }
12313        }
12314        return codeRoot.getPath();
12315    }
12316
12317    /**
12318     * Derive and set the location of native libraries for the given package,
12319     * which varies depending on where and how the package was installed.
12320     */
12321    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12322        final ApplicationInfo info = pkg.applicationInfo;
12323        final String codePath = pkg.codePath;
12324        final File codeFile = new File(codePath);
12325        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12326        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12327
12328        info.nativeLibraryRootDir = null;
12329        info.nativeLibraryRootRequiresIsa = false;
12330        info.nativeLibraryDir = null;
12331        info.secondaryNativeLibraryDir = null;
12332
12333        if (isApkFile(codeFile)) {
12334            // Monolithic install
12335            if (bundledApp) {
12336                // If "/system/lib64/apkname" exists, assume that is the per-package
12337                // native library directory to use; otherwise use "/system/lib/apkname".
12338                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12339                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12340                        getPrimaryInstructionSet(info));
12341
12342                // This is a bundled system app so choose the path based on the ABI.
12343                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12344                // is just the default path.
12345                final String apkName = deriveCodePathName(codePath);
12346                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12347                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12348                        apkName).getAbsolutePath();
12349
12350                if (info.secondaryCpuAbi != null) {
12351                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12352                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12353                            secondaryLibDir, apkName).getAbsolutePath();
12354                }
12355            } else if (asecApp) {
12356                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12357                        .getAbsolutePath();
12358            } else {
12359                final String apkName = deriveCodePathName(codePath);
12360                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12361                        .getAbsolutePath();
12362            }
12363
12364            info.nativeLibraryRootRequiresIsa = false;
12365            info.nativeLibraryDir = info.nativeLibraryRootDir;
12366        } else {
12367            // Cluster install
12368            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12369            info.nativeLibraryRootRequiresIsa = true;
12370
12371            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12372                    getPrimaryInstructionSet(info)).getAbsolutePath();
12373
12374            if (info.secondaryCpuAbi != null) {
12375                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12376                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12377            }
12378        }
12379    }
12380
12381    /**
12382     * Calculate the abis and roots for a bundled app. These can uniquely
12383     * be determined from the contents of the system partition, i.e whether
12384     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12385     * of this information, and instead assume that the system was built
12386     * sensibly.
12387     */
12388    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12389                                           PackageSetting pkgSetting) {
12390        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12391
12392        // If "/system/lib64/apkname" exists, assume that is the per-package
12393        // native library directory to use; otherwise use "/system/lib/apkname".
12394        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12395        setBundledAppAbi(pkg, apkRoot, apkName);
12396        // pkgSetting might be null during rescan following uninstall of updates
12397        // to a bundled app, so accommodate that possibility.  The settings in
12398        // that case will be established later from the parsed package.
12399        //
12400        // If the settings aren't null, sync them up with what we've just derived.
12401        // note that apkRoot isn't stored in the package settings.
12402        if (pkgSetting != null) {
12403            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12404            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12405        }
12406    }
12407
12408    /**
12409     * Deduces the ABI of a bundled app and sets the relevant fields on the
12410     * parsed pkg object.
12411     *
12412     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12413     *        under which system libraries are installed.
12414     * @param apkName the name of the installed package.
12415     */
12416    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12417        final File codeFile = new File(pkg.codePath);
12418
12419        final boolean has64BitLibs;
12420        final boolean has32BitLibs;
12421        if (isApkFile(codeFile)) {
12422            // Monolithic install
12423            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12424            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12425        } else {
12426            // Cluster install
12427            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12428            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12429                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12430                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12431                has64BitLibs = (new File(rootDir, isa)).exists();
12432            } else {
12433                has64BitLibs = false;
12434            }
12435            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12436                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12437                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12438                has32BitLibs = (new File(rootDir, isa)).exists();
12439            } else {
12440                has32BitLibs = false;
12441            }
12442        }
12443
12444        if (has64BitLibs && !has32BitLibs) {
12445            // The package has 64 bit libs, but not 32 bit libs. Its primary
12446            // ABI should be 64 bit. We can safely assume here that the bundled
12447            // native libraries correspond to the most preferred ABI in the list.
12448
12449            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12450            pkg.applicationInfo.secondaryCpuAbi = null;
12451        } else if (has32BitLibs && !has64BitLibs) {
12452            // The package has 32 bit libs but not 64 bit libs. Its primary
12453            // ABI should be 32 bit.
12454
12455            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12456            pkg.applicationInfo.secondaryCpuAbi = null;
12457        } else if (has32BitLibs && has64BitLibs) {
12458            // The application has both 64 and 32 bit bundled libraries. We check
12459            // here that the app declares multiArch support, and warn if it doesn't.
12460            //
12461            // We will be lenient here and record both ABIs. The primary will be the
12462            // ABI that's higher on the list, i.e, a device that's configured to prefer
12463            // 64 bit apps will see a 64 bit primary ABI,
12464
12465            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12466                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12467            }
12468
12469            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12470                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12471                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12472            } else {
12473                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12474                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12475            }
12476        } else {
12477            pkg.applicationInfo.primaryCpuAbi = null;
12478            pkg.applicationInfo.secondaryCpuAbi = null;
12479        }
12480    }
12481
12482    private void killApplication(String pkgName, int appId, String reason) {
12483        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12484    }
12485
12486    private void killApplication(String pkgName, int appId, int userId, String reason) {
12487        // Request the ActivityManager to kill the process(only for existing packages)
12488        // so that we do not end up in a confused state while the user is still using the older
12489        // version of the application while the new one gets installed.
12490        final long token = Binder.clearCallingIdentity();
12491        try {
12492            IActivityManager am = ActivityManager.getService();
12493            if (am != null) {
12494                try {
12495                    am.killApplication(pkgName, appId, userId, reason);
12496                } catch (RemoteException e) {
12497                }
12498            }
12499        } finally {
12500            Binder.restoreCallingIdentity(token);
12501        }
12502    }
12503
12504    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12505        // Remove the parent package setting
12506        PackageSetting ps = (PackageSetting) pkg.mExtras;
12507        if (ps != null) {
12508            removePackageLI(ps, chatty);
12509        }
12510        // Remove the child package setting
12511        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12512        for (int i = 0; i < childCount; i++) {
12513            PackageParser.Package childPkg = pkg.childPackages.get(i);
12514            ps = (PackageSetting) childPkg.mExtras;
12515            if (ps != null) {
12516                removePackageLI(ps, chatty);
12517            }
12518        }
12519    }
12520
12521    void removePackageLI(PackageSetting ps, boolean chatty) {
12522        if (DEBUG_INSTALL) {
12523            if (chatty)
12524                Log.d(TAG, "Removing package " + ps.name);
12525        }
12526
12527        // writer
12528        synchronized (mPackages) {
12529            mPackages.remove(ps.name);
12530            final PackageParser.Package pkg = ps.pkg;
12531            if (pkg != null) {
12532                cleanPackageDataStructuresLILPw(pkg, chatty);
12533            }
12534        }
12535    }
12536
12537    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12538        if (DEBUG_INSTALL) {
12539            if (chatty)
12540                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12541        }
12542
12543        // writer
12544        synchronized (mPackages) {
12545            // Remove the parent package
12546            mPackages.remove(pkg.applicationInfo.packageName);
12547            cleanPackageDataStructuresLILPw(pkg, chatty);
12548
12549            // Remove the child packages
12550            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12551            for (int i = 0; i < childCount; i++) {
12552                PackageParser.Package childPkg = pkg.childPackages.get(i);
12553                mPackages.remove(childPkg.applicationInfo.packageName);
12554                cleanPackageDataStructuresLILPw(childPkg, chatty);
12555            }
12556        }
12557    }
12558
12559    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12560        int N = pkg.providers.size();
12561        StringBuilder r = null;
12562        int i;
12563        for (i=0; i<N; i++) {
12564            PackageParser.Provider p = pkg.providers.get(i);
12565            mProviders.removeProvider(p);
12566            if (p.info.authority == null) {
12567
12568                /* There was another ContentProvider with this authority when
12569                 * this app was installed so this authority is null,
12570                 * Ignore it as we don't have to unregister the provider.
12571                 */
12572                continue;
12573            }
12574            String names[] = p.info.authority.split(";");
12575            for (int j = 0; j < names.length; j++) {
12576                if (mProvidersByAuthority.get(names[j]) == p) {
12577                    mProvidersByAuthority.remove(names[j]);
12578                    if (DEBUG_REMOVE) {
12579                        if (chatty)
12580                            Log.d(TAG, "Unregistered content provider: " + names[j]
12581                                    + ", className = " + p.info.name + ", isSyncable = "
12582                                    + p.info.isSyncable);
12583                    }
12584                }
12585            }
12586            if (DEBUG_REMOVE && chatty) {
12587                if (r == null) {
12588                    r = new StringBuilder(256);
12589                } else {
12590                    r.append(' ');
12591                }
12592                r.append(p.info.name);
12593            }
12594        }
12595        if (r != null) {
12596            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12597        }
12598
12599        N = pkg.services.size();
12600        r = null;
12601        for (i=0; i<N; i++) {
12602            PackageParser.Service s = pkg.services.get(i);
12603            mServices.removeService(s);
12604            if (chatty) {
12605                if (r == null) {
12606                    r = new StringBuilder(256);
12607                } else {
12608                    r.append(' ');
12609                }
12610                r.append(s.info.name);
12611            }
12612        }
12613        if (r != null) {
12614            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12615        }
12616
12617        N = pkg.receivers.size();
12618        r = null;
12619        for (i=0; i<N; i++) {
12620            PackageParser.Activity a = pkg.receivers.get(i);
12621            mReceivers.removeActivity(a, "receiver");
12622            if (DEBUG_REMOVE && chatty) {
12623                if (r == null) {
12624                    r = new StringBuilder(256);
12625                } else {
12626                    r.append(' ');
12627                }
12628                r.append(a.info.name);
12629            }
12630        }
12631        if (r != null) {
12632            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12633        }
12634
12635        N = pkg.activities.size();
12636        r = null;
12637        for (i=0; i<N; i++) {
12638            PackageParser.Activity a = pkg.activities.get(i);
12639            mActivities.removeActivity(a, "activity");
12640            if (DEBUG_REMOVE && chatty) {
12641                if (r == null) {
12642                    r = new StringBuilder(256);
12643                } else {
12644                    r.append(' ');
12645                }
12646                r.append(a.info.name);
12647            }
12648        }
12649        if (r != null) {
12650            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12651        }
12652
12653        N = pkg.permissions.size();
12654        r = null;
12655        for (i=0; i<N; i++) {
12656            PackageParser.Permission p = pkg.permissions.get(i);
12657            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12658            if (bp == null) {
12659                bp = mSettings.mPermissionTrees.get(p.info.name);
12660            }
12661            if (bp != null && bp.perm == p) {
12662                bp.perm = null;
12663                if (DEBUG_REMOVE && chatty) {
12664                    if (r == null) {
12665                        r = new StringBuilder(256);
12666                    } else {
12667                        r.append(' ');
12668                    }
12669                    r.append(p.info.name);
12670                }
12671            }
12672            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12673                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12674                if (appOpPkgs != null) {
12675                    appOpPkgs.remove(pkg.packageName);
12676                }
12677            }
12678        }
12679        if (r != null) {
12680            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12681        }
12682
12683        N = pkg.requestedPermissions.size();
12684        r = null;
12685        for (i=0; i<N; i++) {
12686            String perm = pkg.requestedPermissions.get(i);
12687            BasePermission bp = mSettings.mPermissions.get(perm);
12688            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12689                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12690                if (appOpPkgs != null) {
12691                    appOpPkgs.remove(pkg.packageName);
12692                    if (appOpPkgs.isEmpty()) {
12693                        mAppOpPermissionPackages.remove(perm);
12694                    }
12695                }
12696            }
12697        }
12698        if (r != null) {
12699            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12700        }
12701
12702        N = pkg.instrumentation.size();
12703        r = null;
12704        for (i=0; i<N; i++) {
12705            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12706            mInstrumentation.remove(a.getComponentName());
12707            if (DEBUG_REMOVE && chatty) {
12708                if (r == null) {
12709                    r = new StringBuilder(256);
12710                } else {
12711                    r.append(' ');
12712                }
12713                r.append(a.info.name);
12714            }
12715        }
12716        if (r != null) {
12717            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12718        }
12719
12720        r = null;
12721        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12722            // Only system apps can hold shared libraries.
12723            if (pkg.libraryNames != null) {
12724                for (i = 0; i < pkg.libraryNames.size(); i++) {
12725                    String name = pkg.libraryNames.get(i);
12726                    if (removeSharedLibraryLPw(name, 0)) {
12727                        if (DEBUG_REMOVE && chatty) {
12728                            if (r == null) {
12729                                r = new StringBuilder(256);
12730                            } else {
12731                                r.append(' ');
12732                            }
12733                            r.append(name);
12734                        }
12735                    }
12736                }
12737            }
12738        }
12739
12740        r = null;
12741
12742        // Any package can hold static shared libraries.
12743        if (pkg.staticSharedLibName != null) {
12744            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12745                if (DEBUG_REMOVE && chatty) {
12746                    if (r == null) {
12747                        r = new StringBuilder(256);
12748                    } else {
12749                        r.append(' ');
12750                    }
12751                    r.append(pkg.staticSharedLibName);
12752                }
12753            }
12754        }
12755
12756        if (r != null) {
12757            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12758        }
12759    }
12760
12761    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12762        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12763            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12764                return true;
12765            }
12766        }
12767        return false;
12768    }
12769
12770    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12771    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12772    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12773
12774    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12775        // Update the parent permissions
12776        updatePermissionsLPw(pkg.packageName, pkg, flags);
12777        // Update the child permissions
12778        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12779        for (int i = 0; i < childCount; i++) {
12780            PackageParser.Package childPkg = pkg.childPackages.get(i);
12781            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12782        }
12783    }
12784
12785    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12786            int flags) {
12787        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12788        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12789    }
12790
12791    private void updatePermissionsLPw(String changingPkg,
12792            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12793        // Make sure there are no dangling permission trees.
12794        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12795        while (it.hasNext()) {
12796            final BasePermission bp = it.next();
12797            if (bp.packageSetting == null) {
12798                // We may not yet have parsed the package, so just see if
12799                // we still know about its settings.
12800                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12801            }
12802            if (bp.packageSetting == null) {
12803                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12804                        + " from package " + bp.sourcePackage);
12805                it.remove();
12806            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12807                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12808                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12809                            + " from package " + bp.sourcePackage);
12810                    flags |= UPDATE_PERMISSIONS_ALL;
12811                    it.remove();
12812                }
12813            }
12814        }
12815
12816        // Make sure all dynamic permissions have been assigned to a package,
12817        // and make sure there are no dangling permissions.
12818        it = mSettings.mPermissions.values().iterator();
12819        while (it.hasNext()) {
12820            final BasePermission bp = it.next();
12821            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12822                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12823                        + bp.name + " pkg=" + bp.sourcePackage
12824                        + " info=" + bp.pendingInfo);
12825                if (bp.packageSetting == null && bp.pendingInfo != null) {
12826                    final BasePermission tree = findPermissionTreeLP(bp.name);
12827                    if (tree != null && tree.perm != null) {
12828                        bp.packageSetting = tree.packageSetting;
12829                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12830                                new PermissionInfo(bp.pendingInfo));
12831                        bp.perm.info.packageName = tree.perm.info.packageName;
12832                        bp.perm.info.name = bp.name;
12833                        bp.uid = tree.uid;
12834                    }
12835                }
12836            }
12837            if (bp.packageSetting == null) {
12838                // We may not yet have parsed the package, so just see if
12839                // we still know about its settings.
12840                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12841            }
12842            if (bp.packageSetting == null) {
12843                Slog.w(TAG, "Removing dangling permission: " + bp.name
12844                        + " from package " + bp.sourcePackage);
12845                it.remove();
12846            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12847                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12848                    Slog.i(TAG, "Removing old permission: " + bp.name
12849                            + " from package " + bp.sourcePackage);
12850                    flags |= UPDATE_PERMISSIONS_ALL;
12851                    it.remove();
12852                }
12853            }
12854        }
12855
12856        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12857        // Now update the permissions for all packages, in particular
12858        // replace the granted permissions of the system packages.
12859        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12860            for (PackageParser.Package pkg : mPackages.values()) {
12861                if (pkg != pkgInfo) {
12862                    // Only replace for packages on requested volume
12863                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12864                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12865                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12866                    grantPermissionsLPw(pkg, replace, changingPkg);
12867                }
12868            }
12869        }
12870
12871        if (pkgInfo != null) {
12872            // Only replace for packages on requested volume
12873            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12874            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12875                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12876            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12877        }
12878        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12879    }
12880
12881    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12882            String packageOfInterest) {
12883        // IMPORTANT: There are two types of permissions: install and runtime.
12884        // Install time permissions are granted when the app is installed to
12885        // all device users and users added in the future. Runtime permissions
12886        // are granted at runtime explicitly to specific users. Normal and signature
12887        // protected permissions are install time permissions. Dangerous permissions
12888        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12889        // otherwise they are runtime permissions. This function does not manage
12890        // runtime permissions except for the case an app targeting Lollipop MR1
12891        // being upgraded to target a newer SDK, in which case dangerous permissions
12892        // are transformed from install time to runtime ones.
12893
12894        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12895        if (ps == null) {
12896            return;
12897        }
12898
12899        PermissionsState permissionsState = ps.getPermissionsState();
12900        PermissionsState origPermissions = permissionsState;
12901
12902        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12903
12904        boolean runtimePermissionsRevoked = false;
12905        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12906
12907        boolean changedInstallPermission = false;
12908
12909        if (replace) {
12910            ps.installPermissionsFixed = false;
12911            if (!ps.isSharedUser()) {
12912                origPermissions = new PermissionsState(permissionsState);
12913                permissionsState.reset();
12914            } else {
12915                // We need to know only about runtime permission changes since the
12916                // calling code always writes the install permissions state but
12917                // the runtime ones are written only if changed. The only cases of
12918                // changed runtime permissions here are promotion of an install to
12919                // runtime and revocation of a runtime from a shared user.
12920                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12921                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12922                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12923                    runtimePermissionsRevoked = true;
12924                }
12925            }
12926        }
12927
12928        permissionsState.setGlobalGids(mGlobalGids);
12929
12930        final int N = pkg.requestedPermissions.size();
12931        for (int i=0; i<N; i++) {
12932            final String name = pkg.requestedPermissions.get(i);
12933            final BasePermission bp = mSettings.mPermissions.get(name);
12934            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12935                    >= Build.VERSION_CODES.M;
12936
12937            if (DEBUG_INSTALL) {
12938                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12939            }
12940
12941            if (bp == null || bp.packageSetting == null) {
12942                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12943                    if (DEBUG_PERMISSIONS) {
12944                        Slog.i(TAG, "Unknown permission " + name
12945                                + " in package " + pkg.packageName);
12946                    }
12947                }
12948                continue;
12949            }
12950
12951
12952            // Limit ephemeral apps to ephemeral allowed permissions.
12953            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12954                if (DEBUG_PERMISSIONS) {
12955                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12956                            + pkg.packageName);
12957                }
12958                continue;
12959            }
12960
12961            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12962                if (DEBUG_PERMISSIONS) {
12963                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12964                            + pkg.packageName);
12965                }
12966                continue;
12967            }
12968
12969            final String perm = bp.name;
12970            boolean allowedSig = false;
12971            int grant = GRANT_DENIED;
12972
12973            // Keep track of app op permissions.
12974            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12975                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12976                if (pkgs == null) {
12977                    pkgs = new ArraySet<>();
12978                    mAppOpPermissionPackages.put(bp.name, pkgs);
12979                }
12980                pkgs.add(pkg.packageName);
12981            }
12982
12983            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12984            switch (level) {
12985                case PermissionInfo.PROTECTION_NORMAL: {
12986                    // For all apps normal permissions are install time ones.
12987                    grant = GRANT_INSTALL;
12988                } break;
12989
12990                case PermissionInfo.PROTECTION_DANGEROUS: {
12991                    // If a permission review is required for legacy apps we represent
12992                    // their permissions as always granted runtime ones since we need
12993                    // to keep the review required permission flag per user while an
12994                    // install permission's state is shared across all users.
12995                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12996                        // For legacy apps dangerous permissions are install time ones.
12997                        grant = GRANT_INSTALL;
12998                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12999                        // For legacy apps that became modern, install becomes runtime.
13000                        grant = GRANT_UPGRADE;
13001                    } else if (mPromoteSystemApps
13002                            && isSystemApp(ps)
13003                            && mExistingSystemPackages.contains(ps.name)) {
13004                        // For legacy system apps, install becomes runtime.
13005                        // We cannot check hasInstallPermission() for system apps since those
13006                        // permissions were granted implicitly and not persisted pre-M.
13007                        grant = GRANT_UPGRADE;
13008                    } else {
13009                        // For modern apps keep runtime permissions unchanged.
13010                        grant = GRANT_RUNTIME;
13011                    }
13012                } break;
13013
13014                case PermissionInfo.PROTECTION_SIGNATURE: {
13015                    // For all apps signature permissions are install time ones.
13016                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13017                    if (allowedSig) {
13018                        grant = GRANT_INSTALL;
13019                    }
13020                } break;
13021            }
13022
13023            if (DEBUG_PERMISSIONS) {
13024                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13025            }
13026
13027            if (grant != GRANT_DENIED) {
13028                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13029                    // If this is an existing, non-system package, then
13030                    // we can't add any new permissions to it.
13031                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13032                        // Except...  if this is a permission that was added
13033                        // to the platform (note: need to only do this when
13034                        // updating the platform).
13035                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13036                            grant = GRANT_DENIED;
13037                        }
13038                    }
13039                }
13040
13041                switch (grant) {
13042                    case GRANT_INSTALL: {
13043                        // Revoke this as runtime permission to handle the case of
13044                        // a runtime permission being downgraded to an install one.
13045                        // Also in permission review mode we keep dangerous permissions
13046                        // for legacy apps
13047                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13048                            if (origPermissions.getRuntimePermissionState(
13049                                    bp.name, userId) != null) {
13050                                // Revoke the runtime permission and clear the flags.
13051                                origPermissions.revokeRuntimePermission(bp, userId);
13052                                origPermissions.updatePermissionFlags(bp, userId,
13053                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13054                                // If we revoked a permission permission, we have to write.
13055                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13056                                        changedRuntimePermissionUserIds, userId);
13057                            }
13058                        }
13059                        // Grant an install permission.
13060                        if (permissionsState.grantInstallPermission(bp) !=
13061                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13062                            changedInstallPermission = true;
13063                        }
13064                    } break;
13065
13066                    case GRANT_RUNTIME: {
13067                        // Grant previously granted runtime permissions.
13068                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13069                            PermissionState permissionState = origPermissions
13070                                    .getRuntimePermissionState(bp.name, userId);
13071                            int flags = permissionState != null
13072                                    ? permissionState.getFlags() : 0;
13073                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13074                                // Don't propagate the permission in a permission review mode if
13075                                // the former was revoked, i.e. marked to not propagate on upgrade.
13076                                // Note that in a permission review mode install permissions are
13077                                // represented as constantly granted runtime ones since we need to
13078                                // keep a per user state associated with the permission. Also the
13079                                // revoke on upgrade flag is no longer applicable and is reset.
13080                                final boolean revokeOnUpgrade = (flags & PackageManager
13081                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13082                                if (revokeOnUpgrade) {
13083                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13084                                    // Since we changed the flags, we have to write.
13085                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13086                                            changedRuntimePermissionUserIds, userId);
13087                                }
13088                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13089                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13090                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13091                                        // If we cannot put the permission as it was,
13092                                        // we have to write.
13093                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13094                                                changedRuntimePermissionUserIds, userId);
13095                                    }
13096                                }
13097
13098                                // If the app supports runtime permissions no need for a review.
13099                                if (mPermissionReviewRequired
13100                                        && appSupportsRuntimePermissions
13101                                        && (flags & PackageManager
13102                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13103                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13104                                    // Since we changed the flags, we have to write.
13105                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13106                                            changedRuntimePermissionUserIds, userId);
13107                                }
13108                            } else if (mPermissionReviewRequired
13109                                    && !appSupportsRuntimePermissions) {
13110                                // For legacy apps that need a permission review, every new
13111                                // runtime permission is granted but it is pending a review.
13112                                // We also need to review only platform defined runtime
13113                                // permissions as these are the only ones the platform knows
13114                                // how to disable the API to simulate revocation as legacy
13115                                // apps don't expect to run with revoked permissions.
13116                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13117                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13118                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13119                                        // We changed the flags, hence have to write.
13120                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13121                                                changedRuntimePermissionUserIds, userId);
13122                                    }
13123                                }
13124                                if (permissionsState.grantRuntimePermission(bp, userId)
13125                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13126                                    // We changed the permission, hence have to write.
13127                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13128                                            changedRuntimePermissionUserIds, userId);
13129                                }
13130                            }
13131                            // Propagate the permission flags.
13132                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13133                        }
13134                    } break;
13135
13136                    case GRANT_UPGRADE: {
13137                        // Grant runtime permissions for a previously held install permission.
13138                        PermissionState permissionState = origPermissions
13139                                .getInstallPermissionState(bp.name);
13140                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13141
13142                        if (origPermissions.revokeInstallPermission(bp)
13143                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13144                            // We will be transferring the permission flags, so clear them.
13145                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13146                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13147                            changedInstallPermission = true;
13148                        }
13149
13150                        // If the permission is not to be promoted to runtime we ignore it and
13151                        // also its other flags as they are not applicable to install permissions.
13152                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13153                            for (int userId : currentUserIds) {
13154                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13155                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13156                                    // Transfer the permission flags.
13157                                    permissionsState.updatePermissionFlags(bp, userId,
13158                                            flags, flags);
13159                                    // If we granted the permission, we have to write.
13160                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13161                                            changedRuntimePermissionUserIds, userId);
13162                                }
13163                            }
13164                        }
13165                    } break;
13166
13167                    default: {
13168                        if (packageOfInterest == null
13169                                || packageOfInterest.equals(pkg.packageName)) {
13170                            if (DEBUG_PERMISSIONS) {
13171                                Slog.i(TAG, "Not granting permission " + perm
13172                                        + " to package " + pkg.packageName
13173                                        + " because it was previously installed without");
13174                            }
13175                        }
13176                    } break;
13177                }
13178            } else {
13179                if (permissionsState.revokeInstallPermission(bp) !=
13180                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13181                    // Also drop the permission flags.
13182                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13183                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13184                    changedInstallPermission = true;
13185                    Slog.i(TAG, "Un-granting permission " + perm
13186                            + " from package " + pkg.packageName
13187                            + " (protectionLevel=" + bp.protectionLevel
13188                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13189                            + ")");
13190                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13191                    // Don't print warning for app op permissions, since it is fine for them
13192                    // not to be granted, there is a UI for the user to decide.
13193                    if (DEBUG_PERMISSIONS
13194                            && (packageOfInterest == null
13195                                    || packageOfInterest.equals(pkg.packageName))) {
13196                        Slog.i(TAG, "Not granting permission " + perm
13197                                + " to package " + pkg.packageName
13198                                + " (protectionLevel=" + bp.protectionLevel
13199                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13200                                + ")");
13201                    }
13202                }
13203            }
13204        }
13205
13206        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13207                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13208            // This is the first that we have heard about this package, so the
13209            // permissions we have now selected are fixed until explicitly
13210            // changed.
13211            ps.installPermissionsFixed = true;
13212        }
13213
13214        // Persist the runtime permissions state for users with changes. If permissions
13215        // were revoked because no app in the shared user declares them we have to
13216        // write synchronously to avoid losing runtime permissions state.
13217        for (int userId : changedRuntimePermissionUserIds) {
13218            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13219        }
13220    }
13221
13222    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13223        boolean allowed = false;
13224        final int NP = PackageParser.NEW_PERMISSIONS.length;
13225        for (int ip=0; ip<NP; ip++) {
13226            final PackageParser.NewPermissionInfo npi
13227                    = PackageParser.NEW_PERMISSIONS[ip];
13228            if (npi.name.equals(perm)
13229                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13230                allowed = true;
13231                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13232                        + pkg.packageName);
13233                break;
13234            }
13235        }
13236        return allowed;
13237    }
13238
13239    /**
13240     * Determines whether a package is whitelisted for a particular privapp permission.
13241     *
13242     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
13243     *
13244     * <p>This handles parent/child apps.
13245     */
13246    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
13247        ArraySet<String> wlPermissions = SystemConfig.getInstance()
13248                .getPrivAppPermissions(pkg.packageName);
13249        // Let's check if this package is whitelisted...
13250        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13251        // If it's not, we'll also tail-recurse to the parent.
13252        return whitelisted ||
13253                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
13254    }
13255
13256    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13257            BasePermission bp, PermissionsState origPermissions) {
13258        boolean oemPermission = (bp.protectionLevel
13259                & PermissionInfo.PROTECTION_FLAG_OEM) != 0;
13260        boolean privilegedPermission = (bp.protectionLevel
13261                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13262        boolean privappPermissionsDisable =
13263                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13264        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13265        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13266        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13267                && !platformPackage && platformPermission) {
13268            if (!hasPrivappWhitelistEntry(perm, pkg)) {
13269                Slog.w(TAG, "Privileged permission " + perm + " for package "
13270                        + pkg.packageName + " - not in privapp-permissions whitelist");
13271                // Only report violations for apps on system image
13272                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13273                    // it's only a reportable violation if the permission isn't explicitly denied
13274                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13275                            .getPrivAppDenyPermissions(pkg.packageName);
13276                    final boolean permissionViolation =
13277                            deniedPermissions == null || !deniedPermissions.contains(perm);
13278                    if (permissionViolation) {
13279                        if (mPrivappPermissionsViolations == null) {
13280                            mPrivappPermissionsViolations = new ArraySet<>();
13281                        }
13282                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13283                    } else {
13284                        return false;
13285                    }
13286                }
13287                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13288                    return false;
13289                }
13290            }
13291        }
13292        boolean allowed = (compareSignatures(
13293                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13294                        == PackageManager.SIGNATURE_MATCH)
13295                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13296                        == PackageManager.SIGNATURE_MATCH);
13297        if (!allowed && (privilegedPermission || oemPermission)) {
13298            if (isSystemApp(pkg)) {
13299                // For updated system applications, a privileged/oem permission
13300                // is granted only if it had been defined by the original application.
13301                if (pkg.isUpdatedSystemApp()) {
13302                    final PackageSetting sysPs = mSettings
13303                            .getDisabledSystemPkgLPr(pkg.packageName);
13304                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13305                        // If the original was granted this permission, we take
13306                        // that grant decision as read and propagate it to the
13307                        // update.
13308                        if ((privilegedPermission && sysPs.isPrivileged())
13309                                || (oemPermission && sysPs.isOem()
13310                                        && canGrantOemPermission(sysPs, perm))) {
13311                            allowed = true;
13312                        }
13313                    } else {
13314                        // The system apk may have been updated with an older
13315                        // version of the one on the data partition, but which
13316                        // granted a new system permission that it didn't have
13317                        // before.  In this case we do want to allow the app to
13318                        // now get the new permission if the ancestral apk is
13319                        // privileged to get it.
13320                        if (sysPs != null && sysPs.pkg != null
13321                                && isPackageRequestingPermission(sysPs.pkg, perm)
13322                                && ((privilegedPermission && sysPs.isPrivileged())
13323                                        || (oemPermission && sysPs.isOem()
13324                                                && canGrantOemPermission(sysPs, perm)))) {
13325                            allowed = true;
13326                        }
13327                        // Also if a privileged parent package on the system image or any of
13328                        // its children requested a privileged/oem permission, the updated child
13329                        // packages can also get the permission.
13330                        if (pkg.parentPackage != null) {
13331                            final PackageSetting disabledSysParentPs = mSettings
13332                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13333                            final PackageParser.Package disabledSysParentPkg =
13334                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
13335                                    ? null : disabledSysParentPs.pkg;
13336                            if (disabledSysParentPkg != null
13337                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
13338                                            || (oemPermission && disabledSysParentPs.isOem()))) {
13339                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
13340                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
13341                                    allowed = true;
13342                                } else if (disabledSysParentPkg.childPackages != null) {
13343                                    final int count = disabledSysParentPkg.childPackages.size();
13344                                    for (int i = 0; i < count; i++) {
13345                                        final PackageParser.Package disabledSysChildPkg =
13346                                                disabledSysParentPkg.childPackages.get(i);
13347                                        final PackageSetting disabledSysChildPs =
13348                                                mSettings.getDisabledSystemPkgLPr(
13349                                                        disabledSysChildPkg.packageName);
13350                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
13351                                                && canGrantOemPermission(
13352                                                        disabledSysChildPs, perm)) {
13353                                            allowed = true;
13354                                            break;
13355                                        }
13356                                    }
13357                                }
13358                            }
13359                        }
13360                    }
13361                } else {
13362                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
13363                            || (oemPermission && isOemApp(pkg)
13364                                    && canGrantOemPermission(
13365                                            mSettings.getPackageLPr(pkg.packageName), perm));
13366                }
13367            }
13368        }
13369        if (!allowed) {
13370            if (!allowed && (bp.protectionLevel
13371                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13372                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13373                // If this was a previously normal/dangerous permission that got moved
13374                // to a system permission as part of the runtime permission redesign, then
13375                // we still want to blindly grant it to old apps.
13376                allowed = true;
13377            }
13378            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13379                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13380                // If this permission is to be granted to the system installer and
13381                // this app is an installer, then it gets the permission.
13382                allowed = true;
13383            }
13384            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13385                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13386                // If this permission is to be granted to the system verifier and
13387                // this app is a verifier, then it gets the permission.
13388                allowed = true;
13389            }
13390            if (!allowed && (bp.protectionLevel
13391                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13392                    && isSystemApp(pkg)) {
13393                // Any pre-installed system app is allowed to get this permission.
13394                allowed = true;
13395            }
13396            if (!allowed && (bp.protectionLevel
13397                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13398                // For development permissions, a development permission
13399                // is granted only if it was already granted.
13400                allowed = origPermissions.hasInstallPermission(perm);
13401            }
13402            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13403                    && pkg.packageName.equals(mSetupWizardPackage)) {
13404                // If this permission is to be granted to the system setup wizard and
13405                // this app is a setup wizard, then it gets the permission.
13406                allowed = true;
13407            }
13408        }
13409        return allowed;
13410    }
13411
13412    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
13413        if (!ps.isOem()) {
13414            return false;
13415        }
13416        // all oem permissions must explicitly be granted or denied
13417        final Boolean granted =
13418                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
13419        if (granted == null) {
13420            throw new IllegalStateException("OEM permission" + permission + " requested by package "
13421                    + ps.name + " must be explicitly declared granted or not");
13422        }
13423        return Boolean.TRUE == granted;
13424    }
13425
13426    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13427        final int permCount = pkg.requestedPermissions.size();
13428        for (int j = 0; j < permCount; j++) {
13429            String requestedPermission = pkg.requestedPermissions.get(j);
13430            if (permission.equals(requestedPermission)) {
13431                return true;
13432            }
13433        }
13434        return false;
13435    }
13436
13437    final class ActivityIntentResolver
13438            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13439        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13440                boolean defaultOnly, int userId) {
13441            if (!sUserManager.exists(userId)) return null;
13442            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13443            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13444        }
13445
13446        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13447                int userId) {
13448            if (!sUserManager.exists(userId)) return null;
13449            mFlags = flags;
13450            return super.queryIntent(intent, resolvedType,
13451                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13452                    userId);
13453        }
13454
13455        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13456                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13457            if (!sUserManager.exists(userId)) return null;
13458            if (packageActivities == null) {
13459                return null;
13460            }
13461            mFlags = flags;
13462            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13463            final int N = packageActivities.size();
13464            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13465                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13466
13467            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13468            for (int i = 0; i < N; ++i) {
13469                intentFilters = packageActivities.get(i).intents;
13470                if (intentFilters != null && intentFilters.size() > 0) {
13471                    PackageParser.ActivityIntentInfo[] array =
13472                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13473                    intentFilters.toArray(array);
13474                    listCut.add(array);
13475                }
13476            }
13477            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13478        }
13479
13480        /**
13481         * Finds a privileged activity that matches the specified activity names.
13482         */
13483        private PackageParser.Activity findMatchingActivity(
13484                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13485            for (PackageParser.Activity sysActivity : activityList) {
13486                if (sysActivity.info.name.equals(activityInfo.name)) {
13487                    return sysActivity;
13488                }
13489                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13490                    return sysActivity;
13491                }
13492                if (sysActivity.info.targetActivity != null) {
13493                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13494                        return sysActivity;
13495                    }
13496                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13497                        return sysActivity;
13498                    }
13499                }
13500            }
13501            return null;
13502        }
13503
13504        public class IterGenerator<E> {
13505            public Iterator<E> generate(ActivityIntentInfo info) {
13506                return null;
13507            }
13508        }
13509
13510        public class ActionIterGenerator extends IterGenerator<String> {
13511            @Override
13512            public Iterator<String> generate(ActivityIntentInfo info) {
13513                return info.actionsIterator();
13514            }
13515        }
13516
13517        public class CategoriesIterGenerator extends IterGenerator<String> {
13518            @Override
13519            public Iterator<String> generate(ActivityIntentInfo info) {
13520                return info.categoriesIterator();
13521            }
13522        }
13523
13524        public class SchemesIterGenerator extends IterGenerator<String> {
13525            @Override
13526            public Iterator<String> generate(ActivityIntentInfo info) {
13527                return info.schemesIterator();
13528            }
13529        }
13530
13531        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13532            @Override
13533            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13534                return info.authoritiesIterator();
13535            }
13536        }
13537
13538        /**
13539         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13540         * MODIFIED. Do not pass in a list that should not be changed.
13541         */
13542        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13543                IterGenerator<T> generator, Iterator<T> searchIterator) {
13544            // loop through the set of actions; every one must be found in the intent filter
13545            while (searchIterator.hasNext()) {
13546                // we must have at least one filter in the list to consider a match
13547                if (intentList.size() == 0) {
13548                    break;
13549                }
13550
13551                final T searchAction = searchIterator.next();
13552
13553                // loop through the set of intent filters
13554                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13555                while (intentIter.hasNext()) {
13556                    final ActivityIntentInfo intentInfo = intentIter.next();
13557                    boolean selectionFound = false;
13558
13559                    // loop through the intent filter's selection criteria; at least one
13560                    // of them must match the searched criteria
13561                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13562                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13563                        final T intentSelection = intentSelectionIter.next();
13564                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13565                            selectionFound = true;
13566                            break;
13567                        }
13568                    }
13569
13570                    // the selection criteria wasn't found in this filter's set; this filter
13571                    // is not a potential match
13572                    if (!selectionFound) {
13573                        intentIter.remove();
13574                    }
13575                }
13576            }
13577        }
13578
13579        private boolean isProtectedAction(ActivityIntentInfo filter) {
13580            final Iterator<String> actionsIter = filter.actionsIterator();
13581            while (actionsIter != null && actionsIter.hasNext()) {
13582                final String filterAction = actionsIter.next();
13583                if (PROTECTED_ACTIONS.contains(filterAction)) {
13584                    return true;
13585                }
13586            }
13587            return false;
13588        }
13589
13590        /**
13591         * Adjusts the priority of the given intent filter according to policy.
13592         * <p>
13593         * <ul>
13594         * <li>The priority for non privileged applications is capped to '0'</li>
13595         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13596         * <li>The priority for unbundled updates to privileged applications is capped to the
13597         *      priority defined on the system partition</li>
13598         * </ul>
13599         * <p>
13600         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13601         * allowed to obtain any priority on any action.
13602         */
13603        private void adjustPriority(
13604                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13605            // nothing to do; priority is fine as-is
13606            if (intent.getPriority() <= 0) {
13607                return;
13608            }
13609
13610            final ActivityInfo activityInfo = intent.activity.info;
13611            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13612
13613            final boolean privilegedApp =
13614                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13615            if (!privilegedApp) {
13616                // non-privileged applications can never define a priority >0
13617                if (DEBUG_FILTERS) {
13618                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13619                            + " package: " + applicationInfo.packageName
13620                            + " activity: " + intent.activity.className
13621                            + " origPrio: " + intent.getPriority());
13622                }
13623                intent.setPriority(0);
13624                return;
13625            }
13626
13627            if (systemActivities == null) {
13628                // the system package is not disabled; we're parsing the system partition
13629                if (isProtectedAction(intent)) {
13630                    if (mDeferProtectedFilters) {
13631                        // We can't deal with these just yet. No component should ever obtain a
13632                        // >0 priority for a protected actions, with ONE exception -- the setup
13633                        // wizard. The setup wizard, however, cannot be known until we're able to
13634                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13635                        // until all intent filters have been processed. Chicken, meet egg.
13636                        // Let the filter temporarily have a high priority and rectify the
13637                        // priorities after all system packages have been scanned.
13638                        mProtectedFilters.add(intent);
13639                        if (DEBUG_FILTERS) {
13640                            Slog.i(TAG, "Protected action; save for later;"
13641                                    + " package: " + applicationInfo.packageName
13642                                    + " activity: " + intent.activity.className
13643                                    + " origPrio: " + intent.getPriority());
13644                        }
13645                        return;
13646                    } else {
13647                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13648                            Slog.i(TAG, "No setup wizard;"
13649                                + " All protected intents capped to priority 0");
13650                        }
13651                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13652                            if (DEBUG_FILTERS) {
13653                                Slog.i(TAG, "Found setup wizard;"
13654                                    + " allow priority " + intent.getPriority() + ";"
13655                                    + " package: " + intent.activity.info.packageName
13656                                    + " activity: " + intent.activity.className
13657                                    + " priority: " + intent.getPriority());
13658                            }
13659                            // setup wizard gets whatever it wants
13660                            return;
13661                        }
13662                        if (DEBUG_FILTERS) {
13663                            Slog.i(TAG, "Protected action; cap priority to 0;"
13664                                    + " package: " + intent.activity.info.packageName
13665                                    + " activity: " + intent.activity.className
13666                                    + " origPrio: " + intent.getPriority());
13667                        }
13668                        intent.setPriority(0);
13669                        return;
13670                    }
13671                }
13672                // privileged apps on the system image get whatever priority they request
13673                return;
13674            }
13675
13676            // privileged app unbundled update ... try to find the same activity
13677            final PackageParser.Activity foundActivity =
13678                    findMatchingActivity(systemActivities, activityInfo);
13679            if (foundActivity == null) {
13680                // this is a new activity; it cannot obtain >0 priority
13681                if (DEBUG_FILTERS) {
13682                    Slog.i(TAG, "New activity; cap priority to 0;"
13683                            + " package: " + applicationInfo.packageName
13684                            + " activity: " + intent.activity.className
13685                            + " origPrio: " + intent.getPriority());
13686                }
13687                intent.setPriority(0);
13688                return;
13689            }
13690
13691            // found activity, now check for filter equivalence
13692
13693            // a shallow copy is enough; we modify the list, not its contents
13694            final List<ActivityIntentInfo> intentListCopy =
13695                    new ArrayList<>(foundActivity.intents);
13696            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13697
13698            // find matching action subsets
13699            final Iterator<String> actionsIterator = intent.actionsIterator();
13700            if (actionsIterator != null) {
13701                getIntentListSubset(
13702                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13703                if (intentListCopy.size() == 0) {
13704                    // no more intents to match; we're not equivalent
13705                    if (DEBUG_FILTERS) {
13706                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13707                                + " package: " + applicationInfo.packageName
13708                                + " activity: " + intent.activity.className
13709                                + " origPrio: " + intent.getPriority());
13710                    }
13711                    intent.setPriority(0);
13712                    return;
13713                }
13714            }
13715
13716            // find matching category subsets
13717            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13718            if (categoriesIterator != null) {
13719                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13720                        categoriesIterator);
13721                if (intentListCopy.size() == 0) {
13722                    // no more intents to match; we're not equivalent
13723                    if (DEBUG_FILTERS) {
13724                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13725                                + " package: " + applicationInfo.packageName
13726                                + " activity: " + intent.activity.className
13727                                + " origPrio: " + intent.getPriority());
13728                    }
13729                    intent.setPriority(0);
13730                    return;
13731                }
13732            }
13733
13734            // find matching schemes subsets
13735            final Iterator<String> schemesIterator = intent.schemesIterator();
13736            if (schemesIterator != null) {
13737                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13738                        schemesIterator);
13739                if (intentListCopy.size() == 0) {
13740                    // no more intents to match; we're not equivalent
13741                    if (DEBUG_FILTERS) {
13742                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13743                                + " package: " + applicationInfo.packageName
13744                                + " activity: " + intent.activity.className
13745                                + " origPrio: " + intent.getPriority());
13746                    }
13747                    intent.setPriority(0);
13748                    return;
13749                }
13750            }
13751
13752            // find matching authorities subsets
13753            final Iterator<IntentFilter.AuthorityEntry>
13754                    authoritiesIterator = intent.authoritiesIterator();
13755            if (authoritiesIterator != null) {
13756                getIntentListSubset(intentListCopy,
13757                        new AuthoritiesIterGenerator(),
13758                        authoritiesIterator);
13759                if (intentListCopy.size() == 0) {
13760                    // no more intents to match; we're not equivalent
13761                    if (DEBUG_FILTERS) {
13762                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13763                                + " package: " + applicationInfo.packageName
13764                                + " activity: " + intent.activity.className
13765                                + " origPrio: " + intent.getPriority());
13766                    }
13767                    intent.setPriority(0);
13768                    return;
13769                }
13770            }
13771
13772            // we found matching filter(s); app gets the max priority of all intents
13773            int cappedPriority = 0;
13774            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13775                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13776            }
13777            if (intent.getPriority() > cappedPriority) {
13778                if (DEBUG_FILTERS) {
13779                    Slog.i(TAG, "Found matching filter(s);"
13780                            + " cap priority to " + cappedPriority + ";"
13781                            + " package: " + applicationInfo.packageName
13782                            + " activity: " + intent.activity.className
13783                            + " origPrio: " + intent.getPriority());
13784                }
13785                intent.setPriority(cappedPriority);
13786                return;
13787            }
13788            // all this for nothing; the requested priority was <= what was on the system
13789        }
13790
13791        public final void addActivity(PackageParser.Activity a, String type) {
13792            mActivities.put(a.getComponentName(), a);
13793            if (DEBUG_SHOW_INFO)
13794                Log.v(
13795                TAG, "  " + type + " " +
13796                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13797            if (DEBUG_SHOW_INFO)
13798                Log.v(TAG, "    Class=" + a.info.name);
13799            final int NI = a.intents.size();
13800            for (int j=0; j<NI; j++) {
13801                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13802                if ("activity".equals(type)) {
13803                    final PackageSetting ps =
13804                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13805                    final List<PackageParser.Activity> systemActivities =
13806                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13807                    adjustPriority(systemActivities, intent);
13808                }
13809                if (DEBUG_SHOW_INFO) {
13810                    Log.v(TAG, "    IntentFilter:");
13811                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13812                }
13813                if (!intent.debugCheck()) {
13814                    Log.w(TAG, "==> For Activity " + a.info.name);
13815                }
13816                addFilter(intent);
13817            }
13818        }
13819
13820        public final void removeActivity(PackageParser.Activity a, String type) {
13821            mActivities.remove(a.getComponentName());
13822            if (DEBUG_SHOW_INFO) {
13823                Log.v(TAG, "  " + type + " "
13824                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13825                                : a.info.name) + ":");
13826                Log.v(TAG, "    Class=" + a.info.name);
13827            }
13828            final int NI = a.intents.size();
13829            for (int j=0; j<NI; j++) {
13830                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13831                if (DEBUG_SHOW_INFO) {
13832                    Log.v(TAG, "    IntentFilter:");
13833                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13834                }
13835                removeFilter(intent);
13836            }
13837        }
13838
13839        @Override
13840        protected boolean allowFilterResult(
13841                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13842            ActivityInfo filterAi = filter.activity.info;
13843            for (int i=dest.size()-1; i>=0; i--) {
13844                ActivityInfo destAi = dest.get(i).activityInfo;
13845                if (destAi.name == filterAi.name
13846                        && destAi.packageName == filterAi.packageName) {
13847                    return false;
13848                }
13849            }
13850            return true;
13851        }
13852
13853        @Override
13854        protected ActivityIntentInfo[] newArray(int size) {
13855            return new ActivityIntentInfo[size];
13856        }
13857
13858        @Override
13859        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13860            if (!sUserManager.exists(userId)) return true;
13861            PackageParser.Package p = filter.activity.owner;
13862            if (p != null) {
13863                PackageSetting ps = (PackageSetting)p.mExtras;
13864                if (ps != null) {
13865                    // System apps are never considered stopped for purposes of
13866                    // filtering, because there may be no way for the user to
13867                    // actually re-launch them.
13868                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13869                            && ps.getStopped(userId);
13870                }
13871            }
13872            return false;
13873        }
13874
13875        @Override
13876        protected boolean isPackageForFilter(String packageName,
13877                PackageParser.ActivityIntentInfo info) {
13878            return packageName.equals(info.activity.owner.packageName);
13879        }
13880
13881        @Override
13882        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13883                int match, int userId) {
13884            if (!sUserManager.exists(userId)) return null;
13885            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13886                return null;
13887            }
13888            final PackageParser.Activity activity = info.activity;
13889            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13890            if (ps == null) {
13891                return null;
13892            }
13893            final PackageUserState userState = ps.readUserState(userId);
13894            ActivityInfo ai =
13895                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13896            if (ai == null) {
13897                return null;
13898            }
13899            final boolean matchExplicitlyVisibleOnly =
13900                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13901            final boolean matchVisibleToInstantApp =
13902                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13903            final boolean componentVisible =
13904                    matchVisibleToInstantApp
13905                    && info.isVisibleToInstantApp()
13906                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13907            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13908            // throw out filters that aren't visible to ephemeral apps
13909            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13910                return null;
13911            }
13912            // throw out instant app filters if we're not explicitly requesting them
13913            if (!matchInstantApp && userState.instantApp) {
13914                return null;
13915            }
13916            // throw out instant app filters if updates are available; will trigger
13917            // instant app resolution
13918            if (userState.instantApp && ps.isUpdateAvailable()) {
13919                return null;
13920            }
13921            final ResolveInfo res = new ResolveInfo();
13922            res.activityInfo = ai;
13923            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13924                res.filter = info;
13925            }
13926            if (info != null) {
13927                res.handleAllWebDataURI = info.handleAllWebDataURI();
13928            }
13929            res.priority = info.getPriority();
13930            res.preferredOrder = activity.owner.mPreferredOrder;
13931            //System.out.println("Result: " + res.activityInfo.className +
13932            //                   " = " + res.priority);
13933            res.match = match;
13934            res.isDefault = info.hasDefault;
13935            res.labelRes = info.labelRes;
13936            res.nonLocalizedLabel = info.nonLocalizedLabel;
13937            if (userNeedsBadging(userId)) {
13938                res.noResourceId = true;
13939            } else {
13940                res.icon = info.icon;
13941            }
13942            res.iconResourceId = info.icon;
13943            res.system = res.activityInfo.applicationInfo.isSystemApp();
13944            res.isInstantAppAvailable = userState.instantApp;
13945            return res;
13946        }
13947
13948        @Override
13949        protected void sortResults(List<ResolveInfo> results) {
13950            Collections.sort(results, mResolvePrioritySorter);
13951        }
13952
13953        @Override
13954        protected void dumpFilter(PrintWriter out, String prefix,
13955                PackageParser.ActivityIntentInfo filter) {
13956            out.print(prefix); out.print(
13957                    Integer.toHexString(System.identityHashCode(filter.activity)));
13958                    out.print(' ');
13959                    filter.activity.printComponentShortName(out);
13960                    out.print(" filter ");
13961                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13962        }
13963
13964        @Override
13965        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13966            return filter.activity;
13967        }
13968
13969        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13970            PackageParser.Activity activity = (PackageParser.Activity)label;
13971            out.print(prefix); out.print(
13972                    Integer.toHexString(System.identityHashCode(activity)));
13973                    out.print(' ');
13974                    activity.printComponentShortName(out);
13975            if (count > 1) {
13976                out.print(" ("); out.print(count); out.print(" filters)");
13977            }
13978            out.println();
13979        }
13980
13981        // Keys are String (activity class name), values are Activity.
13982        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13983                = new ArrayMap<ComponentName, PackageParser.Activity>();
13984        private int mFlags;
13985    }
13986
13987    private final class ServiceIntentResolver
13988            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13989        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13990                boolean defaultOnly, int userId) {
13991            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13992            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13993        }
13994
13995        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13996                int userId) {
13997            if (!sUserManager.exists(userId)) return null;
13998            mFlags = flags;
13999            return super.queryIntent(intent, resolvedType,
14000                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14001                    userId);
14002        }
14003
14004        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14005                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
14006            if (!sUserManager.exists(userId)) return null;
14007            if (packageServices == null) {
14008                return null;
14009            }
14010            mFlags = flags;
14011            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
14012            final int N = packageServices.size();
14013            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
14014                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
14015
14016            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
14017            for (int i = 0; i < N; ++i) {
14018                intentFilters = packageServices.get(i).intents;
14019                if (intentFilters != null && intentFilters.size() > 0) {
14020                    PackageParser.ServiceIntentInfo[] array =
14021                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
14022                    intentFilters.toArray(array);
14023                    listCut.add(array);
14024                }
14025            }
14026            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14027        }
14028
14029        public final void addService(PackageParser.Service s) {
14030            mServices.put(s.getComponentName(), s);
14031            if (DEBUG_SHOW_INFO) {
14032                Log.v(TAG, "  "
14033                        + (s.info.nonLocalizedLabel != null
14034                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14035                Log.v(TAG, "    Class=" + s.info.name);
14036            }
14037            final int NI = s.intents.size();
14038            int j;
14039            for (j=0; j<NI; j++) {
14040                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14041                if (DEBUG_SHOW_INFO) {
14042                    Log.v(TAG, "    IntentFilter:");
14043                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14044                }
14045                if (!intent.debugCheck()) {
14046                    Log.w(TAG, "==> For Service " + s.info.name);
14047                }
14048                addFilter(intent);
14049            }
14050        }
14051
14052        public final void removeService(PackageParser.Service s) {
14053            mServices.remove(s.getComponentName());
14054            if (DEBUG_SHOW_INFO) {
14055                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14056                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14057                Log.v(TAG, "    Class=" + s.info.name);
14058            }
14059            final int NI = s.intents.size();
14060            int j;
14061            for (j=0; j<NI; j++) {
14062                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14063                if (DEBUG_SHOW_INFO) {
14064                    Log.v(TAG, "    IntentFilter:");
14065                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14066                }
14067                removeFilter(intent);
14068            }
14069        }
14070
14071        @Override
14072        protected boolean allowFilterResult(
14073                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14074            ServiceInfo filterSi = filter.service.info;
14075            for (int i=dest.size()-1; i>=0; i--) {
14076                ServiceInfo destAi = dest.get(i).serviceInfo;
14077                if (destAi.name == filterSi.name
14078                        && destAi.packageName == filterSi.packageName) {
14079                    return false;
14080                }
14081            }
14082            return true;
14083        }
14084
14085        @Override
14086        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14087            return new PackageParser.ServiceIntentInfo[size];
14088        }
14089
14090        @Override
14091        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14092            if (!sUserManager.exists(userId)) return true;
14093            PackageParser.Package p = filter.service.owner;
14094            if (p != null) {
14095                PackageSetting ps = (PackageSetting)p.mExtras;
14096                if (ps != null) {
14097                    // System apps are never considered stopped for purposes of
14098                    // filtering, because there may be no way for the user to
14099                    // actually re-launch them.
14100                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14101                            && ps.getStopped(userId);
14102                }
14103            }
14104            return false;
14105        }
14106
14107        @Override
14108        protected boolean isPackageForFilter(String packageName,
14109                PackageParser.ServiceIntentInfo info) {
14110            return packageName.equals(info.service.owner.packageName);
14111        }
14112
14113        @Override
14114        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14115                int match, int userId) {
14116            if (!sUserManager.exists(userId)) return null;
14117            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14118            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14119                return null;
14120            }
14121            final PackageParser.Service service = info.service;
14122            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14123            if (ps == null) {
14124                return null;
14125            }
14126            final PackageUserState userState = ps.readUserState(userId);
14127            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14128                    userState, userId);
14129            if (si == null) {
14130                return null;
14131            }
14132            final boolean matchVisibleToInstantApp =
14133                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14134            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14135            // throw out filters that aren't visible to ephemeral apps
14136            if (matchVisibleToInstantApp
14137                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14138                return null;
14139            }
14140            // throw out ephemeral filters if we're not explicitly requesting them
14141            if (!isInstantApp && userState.instantApp) {
14142                return null;
14143            }
14144            // throw out instant app filters if updates are available; will trigger
14145            // instant app resolution
14146            if (userState.instantApp && ps.isUpdateAvailable()) {
14147                return null;
14148            }
14149            final ResolveInfo res = new ResolveInfo();
14150            res.serviceInfo = si;
14151            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14152                res.filter = filter;
14153            }
14154            res.priority = info.getPriority();
14155            res.preferredOrder = service.owner.mPreferredOrder;
14156            res.match = match;
14157            res.isDefault = info.hasDefault;
14158            res.labelRes = info.labelRes;
14159            res.nonLocalizedLabel = info.nonLocalizedLabel;
14160            res.icon = info.icon;
14161            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14162            return res;
14163        }
14164
14165        @Override
14166        protected void sortResults(List<ResolveInfo> results) {
14167            Collections.sort(results, mResolvePrioritySorter);
14168        }
14169
14170        @Override
14171        protected void dumpFilter(PrintWriter out, String prefix,
14172                PackageParser.ServiceIntentInfo filter) {
14173            out.print(prefix); out.print(
14174                    Integer.toHexString(System.identityHashCode(filter.service)));
14175                    out.print(' ');
14176                    filter.service.printComponentShortName(out);
14177                    out.print(" filter ");
14178                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14179        }
14180
14181        @Override
14182        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14183            return filter.service;
14184        }
14185
14186        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14187            PackageParser.Service service = (PackageParser.Service)label;
14188            out.print(prefix); out.print(
14189                    Integer.toHexString(System.identityHashCode(service)));
14190                    out.print(' ');
14191                    service.printComponentShortName(out);
14192            if (count > 1) {
14193                out.print(" ("); out.print(count); out.print(" filters)");
14194            }
14195            out.println();
14196        }
14197
14198//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14199//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14200//            final List<ResolveInfo> retList = Lists.newArrayList();
14201//            while (i.hasNext()) {
14202//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14203//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14204//                    retList.add(resolveInfo);
14205//                }
14206//            }
14207//            return retList;
14208//        }
14209
14210        // Keys are String (activity class name), values are Activity.
14211        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14212                = new ArrayMap<ComponentName, PackageParser.Service>();
14213        private int mFlags;
14214    }
14215
14216    private final class ProviderIntentResolver
14217            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14218        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14219                boolean defaultOnly, int userId) {
14220            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14221            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14222        }
14223
14224        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14225                int userId) {
14226            if (!sUserManager.exists(userId))
14227                return null;
14228            mFlags = flags;
14229            return super.queryIntent(intent, resolvedType,
14230                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14231                    userId);
14232        }
14233
14234        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14235                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14236            if (!sUserManager.exists(userId))
14237                return null;
14238            if (packageProviders == null) {
14239                return null;
14240            }
14241            mFlags = flags;
14242            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14243            final int N = packageProviders.size();
14244            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14245                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14246
14247            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14248            for (int i = 0; i < N; ++i) {
14249                intentFilters = packageProviders.get(i).intents;
14250                if (intentFilters != null && intentFilters.size() > 0) {
14251                    PackageParser.ProviderIntentInfo[] array =
14252                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14253                    intentFilters.toArray(array);
14254                    listCut.add(array);
14255                }
14256            }
14257            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14258        }
14259
14260        public final void addProvider(PackageParser.Provider p) {
14261            if (mProviders.containsKey(p.getComponentName())) {
14262                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14263                return;
14264            }
14265
14266            mProviders.put(p.getComponentName(), p);
14267            if (DEBUG_SHOW_INFO) {
14268                Log.v(TAG, "  "
14269                        + (p.info.nonLocalizedLabel != null
14270                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14271                Log.v(TAG, "    Class=" + p.info.name);
14272            }
14273            final int NI = p.intents.size();
14274            int j;
14275            for (j = 0; j < NI; j++) {
14276                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14277                if (DEBUG_SHOW_INFO) {
14278                    Log.v(TAG, "    IntentFilter:");
14279                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14280                }
14281                if (!intent.debugCheck()) {
14282                    Log.w(TAG, "==> For Provider " + p.info.name);
14283                }
14284                addFilter(intent);
14285            }
14286        }
14287
14288        public final void removeProvider(PackageParser.Provider p) {
14289            mProviders.remove(p.getComponentName());
14290            if (DEBUG_SHOW_INFO) {
14291                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14292                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14293                Log.v(TAG, "    Class=" + p.info.name);
14294            }
14295            final int NI = p.intents.size();
14296            int j;
14297            for (j = 0; j < NI; j++) {
14298                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14299                if (DEBUG_SHOW_INFO) {
14300                    Log.v(TAG, "    IntentFilter:");
14301                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14302                }
14303                removeFilter(intent);
14304            }
14305        }
14306
14307        @Override
14308        protected boolean allowFilterResult(
14309                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14310            ProviderInfo filterPi = filter.provider.info;
14311            for (int i = dest.size() - 1; i >= 0; i--) {
14312                ProviderInfo destPi = dest.get(i).providerInfo;
14313                if (destPi.name == filterPi.name
14314                        && destPi.packageName == filterPi.packageName) {
14315                    return false;
14316                }
14317            }
14318            return true;
14319        }
14320
14321        @Override
14322        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14323            return new PackageParser.ProviderIntentInfo[size];
14324        }
14325
14326        @Override
14327        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14328            if (!sUserManager.exists(userId))
14329                return true;
14330            PackageParser.Package p = filter.provider.owner;
14331            if (p != null) {
14332                PackageSetting ps = (PackageSetting) p.mExtras;
14333                if (ps != null) {
14334                    // System apps are never considered stopped for purposes of
14335                    // filtering, because there may be no way for the user to
14336                    // actually re-launch them.
14337                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14338                            && ps.getStopped(userId);
14339                }
14340            }
14341            return false;
14342        }
14343
14344        @Override
14345        protected boolean isPackageForFilter(String packageName,
14346                PackageParser.ProviderIntentInfo info) {
14347            return packageName.equals(info.provider.owner.packageName);
14348        }
14349
14350        @Override
14351        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14352                int match, int userId) {
14353            if (!sUserManager.exists(userId))
14354                return null;
14355            final PackageParser.ProviderIntentInfo info = filter;
14356            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14357                return null;
14358            }
14359            final PackageParser.Provider provider = info.provider;
14360            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14361            if (ps == null) {
14362                return null;
14363            }
14364            final PackageUserState userState = ps.readUserState(userId);
14365            final boolean matchVisibleToInstantApp =
14366                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14367            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14368            // throw out filters that aren't visible to instant applications
14369            if (matchVisibleToInstantApp
14370                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14371                return null;
14372            }
14373            // throw out instant application filters if we're not explicitly requesting them
14374            if (!isInstantApp && userState.instantApp) {
14375                return null;
14376            }
14377            // throw out instant application filters if updates are available; will trigger
14378            // instant application resolution
14379            if (userState.instantApp && ps.isUpdateAvailable()) {
14380                return null;
14381            }
14382            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14383                    userState, userId);
14384            if (pi == null) {
14385                return null;
14386            }
14387            final ResolveInfo res = new ResolveInfo();
14388            res.providerInfo = pi;
14389            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14390                res.filter = filter;
14391            }
14392            res.priority = info.getPriority();
14393            res.preferredOrder = provider.owner.mPreferredOrder;
14394            res.match = match;
14395            res.isDefault = info.hasDefault;
14396            res.labelRes = info.labelRes;
14397            res.nonLocalizedLabel = info.nonLocalizedLabel;
14398            res.icon = info.icon;
14399            res.system = res.providerInfo.applicationInfo.isSystemApp();
14400            return res;
14401        }
14402
14403        @Override
14404        protected void sortResults(List<ResolveInfo> results) {
14405            Collections.sort(results, mResolvePrioritySorter);
14406        }
14407
14408        @Override
14409        protected void dumpFilter(PrintWriter out, String prefix,
14410                PackageParser.ProviderIntentInfo filter) {
14411            out.print(prefix);
14412            out.print(
14413                    Integer.toHexString(System.identityHashCode(filter.provider)));
14414            out.print(' ');
14415            filter.provider.printComponentShortName(out);
14416            out.print(" filter ");
14417            out.println(Integer.toHexString(System.identityHashCode(filter)));
14418        }
14419
14420        @Override
14421        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14422            return filter.provider;
14423        }
14424
14425        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14426            PackageParser.Provider provider = (PackageParser.Provider)label;
14427            out.print(prefix); out.print(
14428                    Integer.toHexString(System.identityHashCode(provider)));
14429                    out.print(' ');
14430                    provider.printComponentShortName(out);
14431            if (count > 1) {
14432                out.print(" ("); out.print(count); out.print(" filters)");
14433            }
14434            out.println();
14435        }
14436
14437        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14438                = new ArrayMap<ComponentName, PackageParser.Provider>();
14439        private int mFlags;
14440    }
14441
14442    static final class EphemeralIntentResolver
14443            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14444        /**
14445         * The result that has the highest defined order. Ordering applies on a
14446         * per-package basis. Mapping is from package name to Pair of order and
14447         * EphemeralResolveInfo.
14448         * <p>
14449         * NOTE: This is implemented as a field variable for convenience and efficiency.
14450         * By having a field variable, we're able to track filter ordering as soon as
14451         * a non-zero order is defined. Otherwise, multiple loops across the result set
14452         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14453         * this needs to be contained entirely within {@link #filterResults}.
14454         */
14455        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14456
14457        @Override
14458        protected AuxiliaryResolveInfo[] newArray(int size) {
14459            return new AuxiliaryResolveInfo[size];
14460        }
14461
14462        @Override
14463        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14464            return true;
14465        }
14466
14467        @Override
14468        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14469                int userId) {
14470            if (!sUserManager.exists(userId)) {
14471                return null;
14472            }
14473            final String packageName = responseObj.resolveInfo.getPackageName();
14474            final Integer order = responseObj.getOrder();
14475            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14476                    mOrderResult.get(packageName);
14477            // ordering is enabled and this item's order isn't high enough
14478            if (lastOrderResult != null && lastOrderResult.first >= order) {
14479                return null;
14480            }
14481            final InstantAppResolveInfo res = responseObj.resolveInfo;
14482            if (order > 0) {
14483                // non-zero order, enable ordering
14484                mOrderResult.put(packageName, new Pair<>(order, res));
14485            }
14486            return responseObj;
14487        }
14488
14489        @Override
14490        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14491            // only do work if ordering is enabled [most of the time it won't be]
14492            if (mOrderResult.size() == 0) {
14493                return;
14494            }
14495            int resultSize = results.size();
14496            for (int i = 0; i < resultSize; i++) {
14497                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14498                final String packageName = info.getPackageName();
14499                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14500                if (savedInfo == null) {
14501                    // package doesn't having ordering
14502                    continue;
14503                }
14504                if (savedInfo.second == info) {
14505                    // circled back to the highest ordered item; remove from order list
14506                    mOrderResult.remove(packageName);
14507                    if (mOrderResult.size() == 0) {
14508                        // no more ordered items
14509                        break;
14510                    }
14511                    continue;
14512                }
14513                // item has a worse order, remove it from the result list
14514                results.remove(i);
14515                resultSize--;
14516                i--;
14517            }
14518        }
14519    }
14520
14521    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14522            new Comparator<ResolveInfo>() {
14523        public int compare(ResolveInfo r1, ResolveInfo r2) {
14524            int v1 = r1.priority;
14525            int v2 = r2.priority;
14526            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14527            if (v1 != v2) {
14528                return (v1 > v2) ? -1 : 1;
14529            }
14530            v1 = r1.preferredOrder;
14531            v2 = r2.preferredOrder;
14532            if (v1 != v2) {
14533                return (v1 > v2) ? -1 : 1;
14534            }
14535            if (r1.isDefault != r2.isDefault) {
14536                return r1.isDefault ? -1 : 1;
14537            }
14538            v1 = r1.match;
14539            v2 = r2.match;
14540            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14541            if (v1 != v2) {
14542                return (v1 > v2) ? -1 : 1;
14543            }
14544            if (r1.system != r2.system) {
14545                return r1.system ? -1 : 1;
14546            }
14547            if (r1.activityInfo != null) {
14548                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14549            }
14550            if (r1.serviceInfo != null) {
14551                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14552            }
14553            if (r1.providerInfo != null) {
14554                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14555            }
14556            return 0;
14557        }
14558    };
14559
14560    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14561            new Comparator<ProviderInfo>() {
14562        public int compare(ProviderInfo p1, ProviderInfo p2) {
14563            final int v1 = p1.initOrder;
14564            final int v2 = p2.initOrder;
14565            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14566        }
14567    };
14568
14569    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14570            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14571            final int[] userIds) {
14572        mHandler.post(new Runnable() {
14573            @Override
14574            public void run() {
14575                try {
14576                    final IActivityManager am = ActivityManager.getService();
14577                    if (am == null) return;
14578                    final int[] resolvedUserIds;
14579                    if (userIds == null) {
14580                        resolvedUserIds = am.getRunningUserIds();
14581                    } else {
14582                        resolvedUserIds = userIds;
14583                    }
14584                    for (int id : resolvedUserIds) {
14585                        final Intent intent = new Intent(action,
14586                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14587                        if (extras != null) {
14588                            intent.putExtras(extras);
14589                        }
14590                        if (targetPkg != null) {
14591                            intent.setPackage(targetPkg);
14592                        }
14593                        // Modify the UID when posting to other users
14594                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14595                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14596                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14597                            intent.putExtra(Intent.EXTRA_UID, uid);
14598                        }
14599                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14600                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14601                        if (DEBUG_BROADCASTS) {
14602                            RuntimeException here = new RuntimeException("here");
14603                            here.fillInStackTrace();
14604                            Slog.d(TAG, "Sending to user " + id + ": "
14605                                    + intent.toShortString(false, true, false, false)
14606                                    + " " + intent.getExtras(), here);
14607                        }
14608                        am.broadcastIntent(null, intent, null, finishedReceiver,
14609                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14610                                null, finishedReceiver != null, false, id);
14611                    }
14612                } catch (RemoteException ex) {
14613                }
14614            }
14615        });
14616    }
14617
14618    /**
14619     * Check if the external storage media is available. This is true if there
14620     * is a mounted external storage medium or if the external storage is
14621     * emulated.
14622     */
14623    private boolean isExternalMediaAvailable() {
14624        return mMediaMounted || Environment.isExternalStorageEmulated();
14625    }
14626
14627    @Override
14628    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14629        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14630            return null;
14631        }
14632        // writer
14633        synchronized (mPackages) {
14634            if (!isExternalMediaAvailable()) {
14635                // If the external storage is no longer mounted at this point,
14636                // the caller may not have been able to delete all of this
14637                // packages files and can not delete any more.  Bail.
14638                return null;
14639            }
14640            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14641            if (lastPackage != null) {
14642                pkgs.remove(lastPackage);
14643            }
14644            if (pkgs.size() > 0) {
14645                return pkgs.get(0);
14646            }
14647        }
14648        return null;
14649    }
14650
14651    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14652        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14653                userId, andCode ? 1 : 0, packageName);
14654        if (mSystemReady) {
14655            msg.sendToTarget();
14656        } else {
14657            if (mPostSystemReadyMessages == null) {
14658                mPostSystemReadyMessages = new ArrayList<>();
14659            }
14660            mPostSystemReadyMessages.add(msg);
14661        }
14662    }
14663
14664    void startCleaningPackages() {
14665        // reader
14666        if (!isExternalMediaAvailable()) {
14667            return;
14668        }
14669        synchronized (mPackages) {
14670            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14671                return;
14672            }
14673        }
14674        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14675        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14676        IActivityManager am = ActivityManager.getService();
14677        if (am != null) {
14678            int dcsUid = -1;
14679            synchronized (mPackages) {
14680                if (!mDefaultContainerWhitelisted) {
14681                    mDefaultContainerWhitelisted = true;
14682                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14683                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14684                }
14685            }
14686            try {
14687                if (dcsUid > 0) {
14688                    am.backgroundWhitelistUid(dcsUid);
14689                }
14690                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14691                        UserHandle.USER_SYSTEM);
14692            } catch (RemoteException e) {
14693            }
14694        }
14695    }
14696
14697    @Override
14698    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14699            int installFlags, String installerPackageName, int userId) {
14700        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14701
14702        final int callingUid = Binder.getCallingUid();
14703        enforceCrossUserPermission(callingUid, userId,
14704                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14705
14706        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14707            try {
14708                if (observer != null) {
14709                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14710                }
14711            } catch (RemoteException re) {
14712            }
14713            return;
14714        }
14715
14716        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14717            installFlags |= PackageManager.INSTALL_FROM_ADB;
14718
14719        } else {
14720            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14721            // about installerPackageName.
14722
14723            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14724            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14725        }
14726
14727        UserHandle user;
14728        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14729            user = UserHandle.ALL;
14730        } else {
14731            user = new UserHandle(userId);
14732        }
14733
14734        // Only system components can circumvent runtime permissions when installing.
14735        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14736                && mContext.checkCallingOrSelfPermission(Manifest.permission
14737                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14738            throw new SecurityException("You need the "
14739                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14740                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14741        }
14742
14743        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14744                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14745            throw new IllegalArgumentException(
14746                    "New installs into ASEC containers no longer supported");
14747        }
14748
14749        final File originFile = new File(originPath);
14750        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14751
14752        final Message msg = mHandler.obtainMessage(INIT_COPY);
14753        final VerificationInfo verificationInfo = new VerificationInfo(
14754                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14755        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14756                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14757                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14758                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14759        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14760        msg.obj = params;
14761
14762        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14763                System.identityHashCode(msg.obj));
14764        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14765                System.identityHashCode(msg.obj));
14766
14767        mHandler.sendMessage(msg);
14768    }
14769
14770
14771    /**
14772     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14773     * it is acting on behalf on an enterprise or the user).
14774     *
14775     * Note that the ordering of the conditionals in this method is important. The checks we perform
14776     * are as follows, in this order:
14777     *
14778     * 1) If the install is being performed by a system app, we can trust the app to have set the
14779     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14780     *    what it is.
14781     * 2) If the install is being performed by a device or profile owner app, the install reason
14782     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14783     *    set the install reason correctly. If the app targets an older SDK version where install
14784     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14785     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14786     * 3) In all other cases, the install is being performed by a regular app that is neither part
14787     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14788     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14789     *    set to enterprise policy and if so, change it to unknown instead.
14790     */
14791    private int fixUpInstallReason(String installerPackageName, int installerUid,
14792            int installReason) {
14793        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14794                == PERMISSION_GRANTED) {
14795            // If the install is being performed by a system app, we trust that app to have set the
14796            // install reason correctly.
14797            return installReason;
14798        }
14799
14800        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14801            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14802        if (dpm != null) {
14803            ComponentName owner = null;
14804            try {
14805                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14806                if (owner == null) {
14807                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14808                }
14809            } catch (RemoteException e) {
14810            }
14811            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14812                // If the install is being performed by a device or profile owner, the install
14813                // reason should be enterprise policy.
14814                return PackageManager.INSTALL_REASON_POLICY;
14815            }
14816        }
14817
14818        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14819            // If the install is being performed by a regular app (i.e. neither system app nor
14820            // device or profile owner), we have no reason to believe that the app is acting on
14821            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14822            // change it to unknown instead.
14823            return PackageManager.INSTALL_REASON_UNKNOWN;
14824        }
14825
14826        // If the install is being performed by a regular app and the install reason was set to any
14827        // value but enterprise policy, leave the install reason unchanged.
14828        return installReason;
14829    }
14830
14831    void installStage(String packageName, File stagedDir, String stagedCid,
14832            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14833            String installerPackageName, int installerUid, UserHandle user,
14834            Certificate[][] certificates) {
14835        if (DEBUG_EPHEMERAL) {
14836            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14837                Slog.d(TAG, "Ephemeral install of " + packageName);
14838            }
14839        }
14840        final VerificationInfo verificationInfo = new VerificationInfo(
14841                sessionParams.originatingUri, sessionParams.referrerUri,
14842                sessionParams.originatingUid, installerUid);
14843
14844        final OriginInfo origin;
14845        if (stagedDir != null) {
14846            origin = OriginInfo.fromStagedFile(stagedDir);
14847        } else {
14848            origin = OriginInfo.fromStagedContainer(stagedCid);
14849        }
14850
14851        final Message msg = mHandler.obtainMessage(INIT_COPY);
14852        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14853                sessionParams.installReason);
14854        final InstallParams params = new InstallParams(origin, null, observer,
14855                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14856                verificationInfo, user, sessionParams.abiOverride,
14857                sessionParams.grantedRuntimePermissions, certificates, installReason);
14858        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14859        msg.obj = params;
14860
14861        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14862                System.identityHashCode(msg.obj));
14863        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14864                System.identityHashCode(msg.obj));
14865
14866        mHandler.sendMessage(msg);
14867    }
14868
14869    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14870            int userId) {
14871        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14872        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14873                false /*startReceiver*/, pkgSetting.appId, userId);
14874
14875        // Send a session commit broadcast
14876        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14877        info.installReason = pkgSetting.getInstallReason(userId);
14878        info.appPackageName = packageName;
14879        sendSessionCommitBroadcast(info, userId);
14880    }
14881
14882    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14883            boolean includeStopped, int appId, int... userIds) {
14884        if (ArrayUtils.isEmpty(userIds)) {
14885            return;
14886        }
14887        Bundle extras = new Bundle(1);
14888        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14889        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14890
14891        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14892                packageName, extras, 0, null, null, userIds);
14893        if (sendBootCompleted) {
14894            mHandler.post(() -> {
14895                        for (int userId : userIds) {
14896                            sendBootCompletedBroadcastToSystemApp(
14897                                    packageName, includeStopped, userId);
14898                        }
14899                    }
14900            );
14901        }
14902    }
14903
14904    /**
14905     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14906     * automatically without needing an explicit launch.
14907     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14908     */
14909    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14910            int userId) {
14911        // If user is not running, the app didn't miss any broadcast
14912        if (!mUserManagerInternal.isUserRunning(userId)) {
14913            return;
14914        }
14915        final IActivityManager am = ActivityManager.getService();
14916        try {
14917            // Deliver LOCKED_BOOT_COMPLETED first
14918            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14919                    .setPackage(packageName);
14920            if (includeStopped) {
14921                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14922            }
14923            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14924            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14925                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14926
14927            // Deliver BOOT_COMPLETED only if user is unlocked
14928            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14929                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14930                if (includeStopped) {
14931                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14932                }
14933                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14934                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14935            }
14936        } catch (RemoteException e) {
14937            throw e.rethrowFromSystemServer();
14938        }
14939    }
14940
14941    @Override
14942    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14943            int userId) {
14944        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14945        PackageSetting pkgSetting;
14946        final int callingUid = Binder.getCallingUid();
14947        enforceCrossUserPermission(callingUid, userId,
14948                true /* requireFullPermission */, true /* checkShell */,
14949                "setApplicationHiddenSetting for user " + userId);
14950
14951        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14952            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14953            return false;
14954        }
14955
14956        long callingId = Binder.clearCallingIdentity();
14957        try {
14958            boolean sendAdded = false;
14959            boolean sendRemoved = false;
14960            // writer
14961            synchronized (mPackages) {
14962                pkgSetting = mSettings.mPackages.get(packageName);
14963                if (pkgSetting == null) {
14964                    return false;
14965                }
14966                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14967                    return false;
14968                }
14969                // Do not allow "android" is being disabled
14970                if ("android".equals(packageName)) {
14971                    Slog.w(TAG, "Cannot hide package: android");
14972                    return false;
14973                }
14974                // Cannot hide static shared libs as they are considered
14975                // a part of the using app (emulating static linking). Also
14976                // static libs are installed always on internal storage.
14977                PackageParser.Package pkg = mPackages.get(packageName);
14978                if (pkg != null && pkg.staticSharedLibName != null) {
14979                    Slog.w(TAG, "Cannot hide package: " + packageName
14980                            + " providing static shared library: "
14981                            + pkg.staticSharedLibName);
14982                    return false;
14983                }
14984                // Only allow protected packages to hide themselves.
14985                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14986                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14987                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14988                    return false;
14989                }
14990
14991                if (pkgSetting.getHidden(userId) != hidden) {
14992                    pkgSetting.setHidden(hidden, userId);
14993                    mSettings.writePackageRestrictionsLPr(userId);
14994                    if (hidden) {
14995                        sendRemoved = true;
14996                    } else {
14997                        sendAdded = true;
14998                    }
14999                }
15000            }
15001            if (sendAdded) {
15002                sendPackageAddedForUser(packageName, pkgSetting, userId);
15003                return true;
15004            }
15005            if (sendRemoved) {
15006                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
15007                        "hiding pkg");
15008                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
15009                return true;
15010            }
15011        } finally {
15012            Binder.restoreCallingIdentity(callingId);
15013        }
15014        return false;
15015    }
15016
15017    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
15018            int userId) {
15019        final PackageRemovedInfo info = new PackageRemovedInfo(this);
15020        info.removedPackage = packageName;
15021        info.installerPackageName = pkgSetting.installerPackageName;
15022        info.removedUsers = new int[] {userId};
15023        info.broadcastUsers = new int[] {userId};
15024        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15025        info.sendPackageRemovedBroadcasts(true /*killApp*/);
15026    }
15027
15028    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15029        if (pkgList.length > 0) {
15030            Bundle extras = new Bundle(1);
15031            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15032
15033            sendPackageBroadcast(
15034                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15035                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
15036                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15037                    new int[] {userId});
15038        }
15039    }
15040
15041    /**
15042     * Returns true if application is not found or there was an error. Otherwise it returns
15043     * the hidden state of the package for the given user.
15044     */
15045    @Override
15046    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15047        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15048        final int callingUid = Binder.getCallingUid();
15049        enforceCrossUserPermission(callingUid, userId,
15050                true /* requireFullPermission */, false /* checkShell */,
15051                "getApplicationHidden for user " + userId);
15052        PackageSetting ps;
15053        long callingId = Binder.clearCallingIdentity();
15054        try {
15055            // writer
15056            synchronized (mPackages) {
15057                ps = mSettings.mPackages.get(packageName);
15058                if (ps == null) {
15059                    return true;
15060                }
15061                if (filterAppAccessLPr(ps, callingUid, userId)) {
15062                    return true;
15063                }
15064                return ps.getHidden(userId);
15065            }
15066        } finally {
15067            Binder.restoreCallingIdentity(callingId);
15068        }
15069    }
15070
15071    /**
15072     * @hide
15073     */
15074    @Override
15075    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15076            int installReason) {
15077        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15078                null);
15079        PackageSetting pkgSetting;
15080        final int callingUid = Binder.getCallingUid();
15081        enforceCrossUserPermission(callingUid, userId,
15082                true /* requireFullPermission */, true /* checkShell */,
15083                "installExistingPackage for user " + userId);
15084        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15085            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15086        }
15087
15088        long callingId = Binder.clearCallingIdentity();
15089        try {
15090            boolean installed = false;
15091            final boolean instantApp =
15092                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15093            final boolean fullApp =
15094                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15095
15096            // writer
15097            synchronized (mPackages) {
15098                pkgSetting = mSettings.mPackages.get(packageName);
15099                if (pkgSetting == null) {
15100                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15101                }
15102                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15103                    // only allow the existing package to be used if it's installed as a full
15104                    // application for at least one user
15105                    boolean installAllowed = false;
15106                    for (int checkUserId : sUserManager.getUserIds()) {
15107                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15108                        if (installAllowed) {
15109                            break;
15110                        }
15111                    }
15112                    if (!installAllowed) {
15113                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15114                    }
15115                }
15116                if (!pkgSetting.getInstalled(userId)) {
15117                    pkgSetting.setInstalled(true, userId);
15118                    pkgSetting.setHidden(false, userId);
15119                    pkgSetting.setInstallReason(installReason, userId);
15120                    mSettings.writePackageRestrictionsLPr(userId);
15121                    mSettings.writeKernelMappingLPr(pkgSetting);
15122                    installed = true;
15123                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15124                    // upgrade app from instant to full; we don't allow app downgrade
15125                    installed = true;
15126                }
15127                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15128            }
15129
15130            if (installed) {
15131                if (pkgSetting.pkg != null) {
15132                    synchronized (mInstallLock) {
15133                        // We don't need to freeze for a brand new install
15134                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15135                    }
15136                }
15137                sendPackageAddedForUser(packageName, pkgSetting, userId);
15138                synchronized (mPackages) {
15139                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15140                }
15141            }
15142        } finally {
15143            Binder.restoreCallingIdentity(callingId);
15144        }
15145
15146        return PackageManager.INSTALL_SUCCEEDED;
15147    }
15148
15149    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15150            boolean instantApp, boolean fullApp) {
15151        // no state specified; do nothing
15152        if (!instantApp && !fullApp) {
15153            return;
15154        }
15155        if (userId != UserHandle.USER_ALL) {
15156            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15157                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15158            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15159                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15160            }
15161        } else {
15162            for (int currentUserId : sUserManager.getUserIds()) {
15163                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15164                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15165                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15166                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15167                }
15168            }
15169        }
15170    }
15171
15172    boolean isUserRestricted(int userId, String restrictionKey) {
15173        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15174        if (restrictions.getBoolean(restrictionKey, false)) {
15175            Log.w(TAG, "User is restricted: " + restrictionKey);
15176            return true;
15177        }
15178        return false;
15179    }
15180
15181    @Override
15182    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15183            int userId) {
15184        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15185        final int callingUid = Binder.getCallingUid();
15186        enforceCrossUserPermission(callingUid, userId,
15187                true /* requireFullPermission */, true /* checkShell */,
15188                "setPackagesSuspended for user " + userId);
15189
15190        if (ArrayUtils.isEmpty(packageNames)) {
15191            return packageNames;
15192        }
15193
15194        // List of package names for whom the suspended state has changed.
15195        List<String> changedPackages = new ArrayList<>(packageNames.length);
15196        // List of package names for whom the suspended state is not set as requested in this
15197        // method.
15198        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15199        long callingId = Binder.clearCallingIdentity();
15200        try {
15201            for (int i = 0; i < packageNames.length; i++) {
15202                String packageName = packageNames[i];
15203                boolean changed = false;
15204                final int appId;
15205                synchronized (mPackages) {
15206                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15207                    if (pkgSetting == null
15208                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15209                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15210                                + "\". Skipping suspending/un-suspending.");
15211                        unactionedPackages.add(packageName);
15212                        continue;
15213                    }
15214                    appId = pkgSetting.appId;
15215                    if (pkgSetting.getSuspended(userId) != suspended) {
15216                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15217                            unactionedPackages.add(packageName);
15218                            continue;
15219                        }
15220                        pkgSetting.setSuspended(suspended, userId);
15221                        mSettings.writePackageRestrictionsLPr(userId);
15222                        changed = true;
15223                        changedPackages.add(packageName);
15224                    }
15225                }
15226
15227                if (changed && suspended) {
15228                    killApplication(packageName, UserHandle.getUid(userId, appId),
15229                            "suspending package");
15230                }
15231            }
15232        } finally {
15233            Binder.restoreCallingIdentity(callingId);
15234        }
15235
15236        if (!changedPackages.isEmpty()) {
15237            sendPackagesSuspendedForUser(changedPackages.toArray(
15238                    new String[changedPackages.size()]), userId, suspended);
15239        }
15240
15241        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15242    }
15243
15244    @Override
15245    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15246        final int callingUid = Binder.getCallingUid();
15247        enforceCrossUserPermission(callingUid, userId,
15248                true /* requireFullPermission */, false /* checkShell */,
15249                "isPackageSuspendedForUser for user " + userId);
15250        synchronized (mPackages) {
15251            final PackageSetting ps = mSettings.mPackages.get(packageName);
15252            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15253                throw new IllegalArgumentException("Unknown target package: " + packageName);
15254            }
15255            return ps.getSuspended(userId);
15256        }
15257    }
15258
15259    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15260        if (isPackageDeviceAdmin(packageName, userId)) {
15261            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15262                    + "\": has an active device admin");
15263            return false;
15264        }
15265
15266        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15267        if (packageName.equals(activeLauncherPackageName)) {
15268            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15269                    + "\": contains the active launcher");
15270            return false;
15271        }
15272
15273        if (packageName.equals(mRequiredInstallerPackage)) {
15274            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15275                    + "\": required for package installation");
15276            return false;
15277        }
15278
15279        if (packageName.equals(mRequiredUninstallerPackage)) {
15280            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15281                    + "\": required for package uninstallation");
15282            return false;
15283        }
15284
15285        if (packageName.equals(mRequiredVerifierPackage)) {
15286            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15287                    + "\": required for package verification");
15288            return false;
15289        }
15290
15291        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15292            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15293                    + "\": is the default dialer");
15294            return false;
15295        }
15296
15297        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15298            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15299                    + "\": protected package");
15300            return false;
15301        }
15302
15303        // Cannot suspend static shared libs as they are considered
15304        // a part of the using app (emulating static linking). Also
15305        // static libs are installed always on internal storage.
15306        PackageParser.Package pkg = mPackages.get(packageName);
15307        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15308            Slog.w(TAG, "Cannot suspend package: " + packageName
15309                    + " providing static shared library: "
15310                    + pkg.staticSharedLibName);
15311            return false;
15312        }
15313
15314        return true;
15315    }
15316
15317    private String getActiveLauncherPackageName(int userId) {
15318        Intent intent = new Intent(Intent.ACTION_MAIN);
15319        intent.addCategory(Intent.CATEGORY_HOME);
15320        ResolveInfo resolveInfo = resolveIntent(
15321                intent,
15322                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15323                PackageManager.MATCH_DEFAULT_ONLY,
15324                userId);
15325
15326        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15327    }
15328
15329    private String getDefaultDialerPackageName(int userId) {
15330        synchronized (mPackages) {
15331            return mSettings.getDefaultDialerPackageNameLPw(userId);
15332        }
15333    }
15334
15335    @Override
15336    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15337        mContext.enforceCallingOrSelfPermission(
15338                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15339                "Only package verification agents can verify applications");
15340
15341        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15342        final PackageVerificationResponse response = new PackageVerificationResponse(
15343                verificationCode, Binder.getCallingUid());
15344        msg.arg1 = id;
15345        msg.obj = response;
15346        mHandler.sendMessage(msg);
15347    }
15348
15349    @Override
15350    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15351            long millisecondsToDelay) {
15352        mContext.enforceCallingOrSelfPermission(
15353                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15354                "Only package verification agents can extend verification timeouts");
15355
15356        final PackageVerificationState state = mPendingVerification.get(id);
15357        final PackageVerificationResponse response = new PackageVerificationResponse(
15358                verificationCodeAtTimeout, Binder.getCallingUid());
15359
15360        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15361            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15362        }
15363        if (millisecondsToDelay < 0) {
15364            millisecondsToDelay = 0;
15365        }
15366        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15367                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15368            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15369        }
15370
15371        if ((state != null) && !state.timeoutExtended()) {
15372            state.extendTimeout();
15373
15374            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15375            msg.arg1 = id;
15376            msg.obj = response;
15377            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15378        }
15379    }
15380
15381    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15382            int verificationCode, UserHandle user) {
15383        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15384        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15385        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15386        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15387        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15388
15389        mContext.sendBroadcastAsUser(intent, user,
15390                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15391    }
15392
15393    private ComponentName matchComponentForVerifier(String packageName,
15394            List<ResolveInfo> receivers) {
15395        ActivityInfo targetReceiver = null;
15396
15397        final int NR = receivers.size();
15398        for (int i = 0; i < NR; i++) {
15399            final ResolveInfo info = receivers.get(i);
15400            if (info.activityInfo == null) {
15401                continue;
15402            }
15403
15404            if (packageName.equals(info.activityInfo.packageName)) {
15405                targetReceiver = info.activityInfo;
15406                break;
15407            }
15408        }
15409
15410        if (targetReceiver == null) {
15411            return null;
15412        }
15413
15414        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15415    }
15416
15417    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15418            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15419        if (pkgInfo.verifiers.length == 0) {
15420            return null;
15421        }
15422
15423        final int N = pkgInfo.verifiers.length;
15424        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15425        for (int i = 0; i < N; i++) {
15426            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15427
15428            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15429                    receivers);
15430            if (comp == null) {
15431                continue;
15432            }
15433
15434            final int verifierUid = getUidForVerifier(verifierInfo);
15435            if (verifierUid == -1) {
15436                continue;
15437            }
15438
15439            if (DEBUG_VERIFY) {
15440                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15441                        + " with the correct signature");
15442            }
15443            sufficientVerifiers.add(comp);
15444            verificationState.addSufficientVerifier(verifierUid);
15445        }
15446
15447        return sufficientVerifiers;
15448    }
15449
15450    private int getUidForVerifier(VerifierInfo verifierInfo) {
15451        synchronized (mPackages) {
15452            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15453            if (pkg == null) {
15454                return -1;
15455            } else if (pkg.mSignatures.length != 1) {
15456                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15457                        + " has more than one signature; ignoring");
15458                return -1;
15459            }
15460
15461            /*
15462             * If the public key of the package's signature does not match
15463             * our expected public key, then this is a different package and
15464             * we should skip.
15465             */
15466
15467            final byte[] expectedPublicKey;
15468            try {
15469                final Signature verifierSig = pkg.mSignatures[0];
15470                final PublicKey publicKey = verifierSig.getPublicKey();
15471                expectedPublicKey = publicKey.getEncoded();
15472            } catch (CertificateException e) {
15473                return -1;
15474            }
15475
15476            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15477
15478            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15479                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15480                        + " does not have the expected public key; ignoring");
15481                return -1;
15482            }
15483
15484            return pkg.applicationInfo.uid;
15485        }
15486    }
15487
15488    @Override
15489    public void finishPackageInstall(int token, boolean didLaunch) {
15490        enforceSystemOrRoot("Only the system is allowed to finish installs");
15491
15492        if (DEBUG_INSTALL) {
15493            Slog.v(TAG, "BM finishing package install for " + token);
15494        }
15495        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15496
15497        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15498        mHandler.sendMessage(msg);
15499    }
15500
15501    /**
15502     * Get the verification agent timeout.  Used for both the APK verifier and the
15503     * intent filter verifier.
15504     *
15505     * @return verification timeout in milliseconds
15506     */
15507    private long getVerificationTimeout() {
15508        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15509                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15510                DEFAULT_VERIFICATION_TIMEOUT);
15511    }
15512
15513    /**
15514     * Get the default verification agent response code.
15515     *
15516     * @return default verification response code
15517     */
15518    private int getDefaultVerificationResponse(UserHandle user) {
15519        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15520            return PackageManager.VERIFICATION_REJECT;
15521        }
15522        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15523                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15524                DEFAULT_VERIFICATION_RESPONSE);
15525    }
15526
15527    /**
15528     * Check whether or not package verification has been enabled.
15529     *
15530     * @return true if verification should be performed
15531     */
15532    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15533        if (!DEFAULT_VERIFY_ENABLE) {
15534            return false;
15535        }
15536
15537        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15538
15539        // Check if installing from ADB
15540        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15541            // Do not run verification in a test harness environment
15542            if (ActivityManager.isRunningInTestHarness()) {
15543                return false;
15544            }
15545            if (ensureVerifyAppsEnabled) {
15546                return true;
15547            }
15548            // Check if the developer does not want package verification for ADB installs
15549            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15550                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15551                return false;
15552            }
15553        } else {
15554            // only when not installed from ADB, skip verification for instant apps when
15555            // the installer and verifier are the same.
15556            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15557                if (mInstantAppInstallerActivity != null
15558                        && mInstantAppInstallerActivity.packageName.equals(
15559                                mRequiredVerifierPackage)) {
15560                    try {
15561                        mContext.getSystemService(AppOpsManager.class)
15562                                .checkPackage(installerUid, mRequiredVerifierPackage);
15563                        if (DEBUG_VERIFY) {
15564                            Slog.i(TAG, "disable verification for instant app");
15565                        }
15566                        return false;
15567                    } catch (SecurityException ignore) { }
15568                }
15569            }
15570        }
15571
15572        if (ensureVerifyAppsEnabled) {
15573            return true;
15574        }
15575
15576        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15577                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15578    }
15579
15580    @Override
15581    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15582            throws RemoteException {
15583        mContext.enforceCallingOrSelfPermission(
15584                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15585                "Only intentfilter verification agents can verify applications");
15586
15587        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15588        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15589                Binder.getCallingUid(), verificationCode, failedDomains);
15590        msg.arg1 = id;
15591        msg.obj = response;
15592        mHandler.sendMessage(msg);
15593    }
15594
15595    @Override
15596    public int getIntentVerificationStatus(String packageName, int userId) {
15597        final int callingUid = Binder.getCallingUid();
15598        if (UserHandle.getUserId(callingUid) != userId) {
15599            mContext.enforceCallingOrSelfPermission(
15600                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15601                    "getIntentVerificationStatus" + userId);
15602        }
15603        if (getInstantAppPackageName(callingUid) != null) {
15604            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15605        }
15606        synchronized (mPackages) {
15607            final PackageSetting ps = mSettings.mPackages.get(packageName);
15608            if (ps == null
15609                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15610                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15611            }
15612            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15613        }
15614    }
15615
15616    @Override
15617    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15618        mContext.enforceCallingOrSelfPermission(
15619                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15620
15621        boolean result = false;
15622        synchronized (mPackages) {
15623            final PackageSetting ps = mSettings.mPackages.get(packageName);
15624            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15625                return false;
15626            }
15627            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15628        }
15629        if (result) {
15630            scheduleWritePackageRestrictionsLocked(userId);
15631        }
15632        return result;
15633    }
15634
15635    @Override
15636    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15637            String packageName) {
15638        final int callingUid = Binder.getCallingUid();
15639        if (getInstantAppPackageName(callingUid) != null) {
15640            return ParceledListSlice.emptyList();
15641        }
15642        synchronized (mPackages) {
15643            final PackageSetting ps = mSettings.mPackages.get(packageName);
15644            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15645                return ParceledListSlice.emptyList();
15646            }
15647            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15648        }
15649    }
15650
15651    @Override
15652    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15653        if (TextUtils.isEmpty(packageName)) {
15654            return ParceledListSlice.emptyList();
15655        }
15656        final int callingUid = Binder.getCallingUid();
15657        final int callingUserId = UserHandle.getUserId(callingUid);
15658        synchronized (mPackages) {
15659            PackageParser.Package pkg = mPackages.get(packageName);
15660            if (pkg == null || pkg.activities == null) {
15661                return ParceledListSlice.emptyList();
15662            }
15663            if (pkg.mExtras == null) {
15664                return ParceledListSlice.emptyList();
15665            }
15666            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15667            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15668                return ParceledListSlice.emptyList();
15669            }
15670            final int count = pkg.activities.size();
15671            ArrayList<IntentFilter> result = new ArrayList<>();
15672            for (int n=0; n<count; n++) {
15673                PackageParser.Activity activity = pkg.activities.get(n);
15674                if (activity.intents != null && activity.intents.size() > 0) {
15675                    result.addAll(activity.intents);
15676                }
15677            }
15678            return new ParceledListSlice<>(result);
15679        }
15680    }
15681
15682    @Override
15683    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15684        mContext.enforceCallingOrSelfPermission(
15685                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15686        if (UserHandle.getCallingUserId() != userId) {
15687            mContext.enforceCallingOrSelfPermission(
15688                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15689        }
15690
15691        synchronized (mPackages) {
15692            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15693            if (packageName != null) {
15694                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15695                        packageName, userId);
15696            }
15697            return result;
15698        }
15699    }
15700
15701    @Override
15702    public String getDefaultBrowserPackageName(int userId) {
15703        if (UserHandle.getCallingUserId() != userId) {
15704            mContext.enforceCallingOrSelfPermission(
15705                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15706        }
15707        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15708            return null;
15709        }
15710        synchronized (mPackages) {
15711            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15712        }
15713    }
15714
15715    /**
15716     * Get the "allow unknown sources" setting.
15717     *
15718     * @return the current "allow unknown sources" setting
15719     */
15720    private int getUnknownSourcesSettings() {
15721        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15722                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15723                -1);
15724    }
15725
15726    @Override
15727    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15728        final int callingUid = Binder.getCallingUid();
15729        if (getInstantAppPackageName(callingUid) != null) {
15730            return;
15731        }
15732        // writer
15733        synchronized (mPackages) {
15734            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15735            if (targetPackageSetting == null
15736                    || filterAppAccessLPr(
15737                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15738                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15739            }
15740
15741            PackageSetting installerPackageSetting;
15742            if (installerPackageName != null) {
15743                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15744                if (installerPackageSetting == null) {
15745                    throw new IllegalArgumentException("Unknown installer package: "
15746                            + installerPackageName);
15747                }
15748            } else {
15749                installerPackageSetting = null;
15750            }
15751
15752            Signature[] callerSignature;
15753            Object obj = mSettings.getUserIdLPr(callingUid);
15754            if (obj != null) {
15755                if (obj instanceof SharedUserSetting) {
15756                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15757                } else if (obj instanceof PackageSetting) {
15758                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15759                } else {
15760                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15761                }
15762            } else {
15763                throw new SecurityException("Unknown calling UID: " + callingUid);
15764            }
15765
15766            // Verify: can't set installerPackageName to a package that is
15767            // not signed with the same cert as the caller.
15768            if (installerPackageSetting != null) {
15769                if (compareSignatures(callerSignature,
15770                        installerPackageSetting.signatures.mSignatures)
15771                        != PackageManager.SIGNATURE_MATCH) {
15772                    throw new SecurityException(
15773                            "Caller does not have same cert as new installer package "
15774                            + installerPackageName);
15775                }
15776            }
15777
15778            // Verify: if target already has an installer package, it must
15779            // be signed with the same cert as the caller.
15780            if (targetPackageSetting.installerPackageName != null) {
15781                PackageSetting setting = mSettings.mPackages.get(
15782                        targetPackageSetting.installerPackageName);
15783                // If the currently set package isn't valid, then it's always
15784                // okay to change it.
15785                if (setting != null) {
15786                    if (compareSignatures(callerSignature,
15787                            setting.signatures.mSignatures)
15788                            != PackageManager.SIGNATURE_MATCH) {
15789                        throw new SecurityException(
15790                                "Caller does not have same cert as old installer package "
15791                                + targetPackageSetting.installerPackageName);
15792                    }
15793                }
15794            }
15795
15796            // Okay!
15797            targetPackageSetting.installerPackageName = installerPackageName;
15798            if (installerPackageName != null) {
15799                mSettings.mInstallerPackages.add(installerPackageName);
15800            }
15801            scheduleWriteSettingsLocked();
15802        }
15803    }
15804
15805    @Override
15806    public void setApplicationCategoryHint(String packageName, int categoryHint,
15807            String callerPackageName) {
15808        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15809            throw new SecurityException("Instant applications don't have access to this method");
15810        }
15811        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15812                callerPackageName);
15813        synchronized (mPackages) {
15814            PackageSetting ps = mSettings.mPackages.get(packageName);
15815            if (ps == null) {
15816                throw new IllegalArgumentException("Unknown target package " + packageName);
15817            }
15818            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15819                throw new IllegalArgumentException("Unknown target package " + packageName);
15820            }
15821            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15822                throw new IllegalArgumentException("Calling package " + callerPackageName
15823                        + " is not installer for " + packageName);
15824            }
15825
15826            if (ps.categoryHint != categoryHint) {
15827                ps.categoryHint = categoryHint;
15828                scheduleWriteSettingsLocked();
15829            }
15830        }
15831    }
15832
15833    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15834        // Queue up an async operation since the package installation may take a little while.
15835        mHandler.post(new Runnable() {
15836            public void run() {
15837                mHandler.removeCallbacks(this);
15838                 // Result object to be returned
15839                PackageInstalledInfo res = new PackageInstalledInfo();
15840                res.setReturnCode(currentStatus);
15841                res.uid = -1;
15842                res.pkg = null;
15843                res.removedInfo = null;
15844                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15845                    args.doPreInstall(res.returnCode);
15846                    synchronized (mInstallLock) {
15847                        installPackageTracedLI(args, res);
15848                    }
15849                    args.doPostInstall(res.returnCode, res.uid);
15850                }
15851
15852                // A restore should be performed at this point if (a) the install
15853                // succeeded, (b) the operation is not an update, and (c) the new
15854                // package has not opted out of backup participation.
15855                final boolean update = res.removedInfo != null
15856                        && res.removedInfo.removedPackage != null;
15857                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15858                boolean doRestore = !update
15859                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15860
15861                // Set up the post-install work request bookkeeping.  This will be used
15862                // and cleaned up by the post-install event handling regardless of whether
15863                // there's a restore pass performed.  Token values are >= 1.
15864                int token;
15865                if (mNextInstallToken < 0) mNextInstallToken = 1;
15866                token = mNextInstallToken++;
15867
15868                PostInstallData data = new PostInstallData(args, res);
15869                mRunningInstalls.put(token, data);
15870                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15871
15872                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15873                    // Pass responsibility to the Backup Manager.  It will perform a
15874                    // restore if appropriate, then pass responsibility back to the
15875                    // Package Manager to run the post-install observer callbacks
15876                    // and broadcasts.
15877                    IBackupManager bm = IBackupManager.Stub.asInterface(
15878                            ServiceManager.getService(Context.BACKUP_SERVICE));
15879                    if (bm != null) {
15880                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15881                                + " to BM for possible restore");
15882                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15883                        try {
15884                            // TODO: http://b/22388012
15885                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15886                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15887                            } else {
15888                                doRestore = false;
15889                            }
15890                        } catch (RemoteException e) {
15891                            // can't happen; the backup manager is local
15892                        } catch (Exception e) {
15893                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15894                            doRestore = false;
15895                        }
15896                    } else {
15897                        Slog.e(TAG, "Backup Manager not found!");
15898                        doRestore = false;
15899                    }
15900                }
15901
15902                if (!doRestore) {
15903                    // No restore possible, or the Backup Manager was mysteriously not
15904                    // available -- just fire the post-install work request directly.
15905                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15906
15907                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15908
15909                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15910                    mHandler.sendMessage(msg);
15911                }
15912            }
15913        });
15914    }
15915
15916    /**
15917     * Callback from PackageSettings whenever an app is first transitioned out of the
15918     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15919     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15920     * here whether the app is the target of an ongoing install, and only send the
15921     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15922     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15923     * handling.
15924     */
15925    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15926        // Serialize this with the rest of the install-process message chain.  In the
15927        // restore-at-install case, this Runnable will necessarily run before the
15928        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15929        // are coherent.  In the non-restore case, the app has already completed install
15930        // and been launched through some other means, so it is not in a problematic
15931        // state for observers to see the FIRST_LAUNCH signal.
15932        mHandler.post(new Runnable() {
15933            @Override
15934            public void run() {
15935                for (int i = 0; i < mRunningInstalls.size(); i++) {
15936                    final PostInstallData data = mRunningInstalls.valueAt(i);
15937                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15938                        continue;
15939                    }
15940                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15941                        // right package; but is it for the right user?
15942                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15943                            if (userId == data.res.newUsers[uIndex]) {
15944                                if (DEBUG_BACKUP) {
15945                                    Slog.i(TAG, "Package " + pkgName
15946                                            + " being restored so deferring FIRST_LAUNCH");
15947                                }
15948                                return;
15949                            }
15950                        }
15951                    }
15952                }
15953                // didn't find it, so not being restored
15954                if (DEBUG_BACKUP) {
15955                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15956                }
15957                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15958            }
15959        });
15960    }
15961
15962    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15963        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15964                installerPkg, null, userIds);
15965    }
15966
15967    private abstract class HandlerParams {
15968        private static final int MAX_RETRIES = 4;
15969
15970        /**
15971         * Number of times startCopy() has been attempted and had a non-fatal
15972         * error.
15973         */
15974        private int mRetries = 0;
15975
15976        /** User handle for the user requesting the information or installation. */
15977        private final UserHandle mUser;
15978        String traceMethod;
15979        int traceCookie;
15980
15981        HandlerParams(UserHandle user) {
15982            mUser = user;
15983        }
15984
15985        UserHandle getUser() {
15986            return mUser;
15987        }
15988
15989        HandlerParams setTraceMethod(String traceMethod) {
15990            this.traceMethod = traceMethod;
15991            return this;
15992        }
15993
15994        HandlerParams setTraceCookie(int traceCookie) {
15995            this.traceCookie = traceCookie;
15996            return this;
15997        }
15998
15999        final boolean startCopy() {
16000            boolean res;
16001            try {
16002                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
16003
16004                if (++mRetries > MAX_RETRIES) {
16005                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
16006                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
16007                    handleServiceError();
16008                    return false;
16009                } else {
16010                    handleStartCopy();
16011                    res = true;
16012                }
16013            } catch (RemoteException e) {
16014                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
16015                mHandler.sendEmptyMessage(MCS_RECONNECT);
16016                res = false;
16017            }
16018            handleReturnCode();
16019            return res;
16020        }
16021
16022        final void serviceError() {
16023            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16024            handleServiceError();
16025            handleReturnCode();
16026        }
16027
16028        abstract void handleStartCopy() throws RemoteException;
16029        abstract void handleServiceError();
16030        abstract void handleReturnCode();
16031    }
16032
16033    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16034        for (File path : paths) {
16035            try {
16036                mcs.clearDirectory(path.getAbsolutePath());
16037            } catch (RemoteException e) {
16038            }
16039        }
16040    }
16041
16042    static class OriginInfo {
16043        /**
16044         * Location where install is coming from, before it has been
16045         * copied/renamed into place. This could be a single monolithic APK
16046         * file, or a cluster directory. This location may be untrusted.
16047         */
16048        final File file;
16049        final String cid;
16050
16051        /**
16052         * Flag indicating that {@link #file} or {@link #cid} has already been
16053         * staged, meaning downstream users don't need to defensively copy the
16054         * contents.
16055         */
16056        final boolean staged;
16057
16058        /**
16059         * Flag indicating that {@link #file} or {@link #cid} is an already
16060         * installed app that is being moved.
16061         */
16062        final boolean existing;
16063
16064        final String resolvedPath;
16065        final File resolvedFile;
16066
16067        static OriginInfo fromNothing() {
16068            return new OriginInfo(null, null, false, false);
16069        }
16070
16071        static OriginInfo fromUntrustedFile(File file) {
16072            return new OriginInfo(file, null, false, false);
16073        }
16074
16075        static OriginInfo fromExistingFile(File file) {
16076            return new OriginInfo(file, null, false, true);
16077        }
16078
16079        static OriginInfo fromStagedFile(File file) {
16080            return new OriginInfo(file, null, true, false);
16081        }
16082
16083        static OriginInfo fromStagedContainer(String cid) {
16084            return new OriginInfo(null, cid, true, false);
16085        }
16086
16087        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16088            this.file = file;
16089            this.cid = cid;
16090            this.staged = staged;
16091            this.existing = existing;
16092
16093            if (cid != null) {
16094                resolvedPath = PackageHelper.getSdDir(cid);
16095                resolvedFile = new File(resolvedPath);
16096            } else if (file != null) {
16097                resolvedPath = file.getAbsolutePath();
16098                resolvedFile = file;
16099            } else {
16100                resolvedPath = null;
16101                resolvedFile = null;
16102            }
16103        }
16104    }
16105
16106    static class MoveInfo {
16107        final int moveId;
16108        final String fromUuid;
16109        final String toUuid;
16110        final String packageName;
16111        final String dataAppName;
16112        final int appId;
16113        final String seinfo;
16114        final int targetSdkVersion;
16115
16116        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16117                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16118            this.moveId = moveId;
16119            this.fromUuid = fromUuid;
16120            this.toUuid = toUuid;
16121            this.packageName = packageName;
16122            this.dataAppName = dataAppName;
16123            this.appId = appId;
16124            this.seinfo = seinfo;
16125            this.targetSdkVersion = targetSdkVersion;
16126        }
16127    }
16128
16129    static class VerificationInfo {
16130        /** A constant used to indicate that a uid value is not present. */
16131        public static final int NO_UID = -1;
16132
16133        /** URI referencing where the package was downloaded from. */
16134        final Uri originatingUri;
16135
16136        /** HTTP referrer URI associated with the originatingURI. */
16137        final Uri referrer;
16138
16139        /** UID of the application that the install request originated from. */
16140        final int originatingUid;
16141
16142        /** UID of application requesting the install */
16143        final int installerUid;
16144
16145        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16146            this.originatingUri = originatingUri;
16147            this.referrer = referrer;
16148            this.originatingUid = originatingUid;
16149            this.installerUid = installerUid;
16150        }
16151    }
16152
16153    class InstallParams extends HandlerParams {
16154        final OriginInfo origin;
16155        final MoveInfo move;
16156        final IPackageInstallObserver2 observer;
16157        int installFlags;
16158        final String installerPackageName;
16159        final String volumeUuid;
16160        private InstallArgs mArgs;
16161        private int mRet;
16162        final String packageAbiOverride;
16163        final String[] grantedRuntimePermissions;
16164        final VerificationInfo verificationInfo;
16165        final Certificate[][] certificates;
16166        final int installReason;
16167
16168        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16169                int installFlags, String installerPackageName, String volumeUuid,
16170                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16171                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16172            super(user);
16173            this.origin = origin;
16174            this.move = move;
16175            this.observer = observer;
16176            this.installFlags = installFlags;
16177            this.installerPackageName = installerPackageName;
16178            this.volumeUuid = volumeUuid;
16179            this.verificationInfo = verificationInfo;
16180            this.packageAbiOverride = packageAbiOverride;
16181            this.grantedRuntimePermissions = grantedPermissions;
16182            this.certificates = certificates;
16183            this.installReason = installReason;
16184        }
16185
16186        @Override
16187        public String toString() {
16188            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16189                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16190        }
16191
16192        private int installLocationPolicy(PackageInfoLite pkgLite) {
16193            String packageName = pkgLite.packageName;
16194            int installLocation = pkgLite.installLocation;
16195            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16196            // reader
16197            synchronized (mPackages) {
16198                // Currently installed package which the new package is attempting to replace or
16199                // null if no such package is installed.
16200                PackageParser.Package installedPkg = mPackages.get(packageName);
16201                // Package which currently owns the data which the new package will own if installed.
16202                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16203                // will be null whereas dataOwnerPkg will contain information about the package
16204                // which was uninstalled while keeping its data.
16205                PackageParser.Package dataOwnerPkg = installedPkg;
16206                if (dataOwnerPkg  == null) {
16207                    PackageSetting ps = mSettings.mPackages.get(packageName);
16208                    if (ps != null) {
16209                        dataOwnerPkg = ps.pkg;
16210                    }
16211                }
16212
16213                if (dataOwnerPkg != null) {
16214                    // If installed, the package will get access to data left on the device by its
16215                    // predecessor. As a security measure, this is permited only if this is not a
16216                    // version downgrade or if the predecessor package is marked as debuggable and
16217                    // a downgrade is explicitly requested.
16218                    //
16219                    // On debuggable platform builds, downgrades are permitted even for
16220                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16221                    // not offer security guarantees and thus it's OK to disable some security
16222                    // mechanisms to make debugging/testing easier on those builds. However, even on
16223                    // debuggable builds downgrades of packages are permitted only if requested via
16224                    // installFlags. This is because we aim to keep the behavior of debuggable
16225                    // platform builds as close as possible to the behavior of non-debuggable
16226                    // platform builds.
16227                    final boolean downgradeRequested =
16228                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16229                    final boolean packageDebuggable =
16230                                (dataOwnerPkg.applicationInfo.flags
16231                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16232                    final boolean downgradePermitted =
16233                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16234                    if (!downgradePermitted) {
16235                        try {
16236                            checkDowngrade(dataOwnerPkg, pkgLite);
16237                        } catch (PackageManagerException e) {
16238                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16239                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16240                        }
16241                    }
16242                }
16243
16244                if (installedPkg != null) {
16245                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16246                        // Check for updated system application.
16247                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16248                            if (onSd) {
16249                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16250                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16251                            }
16252                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16253                        } else {
16254                            if (onSd) {
16255                                // Install flag overrides everything.
16256                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16257                            }
16258                            // If current upgrade specifies particular preference
16259                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16260                                // Application explicitly specified internal.
16261                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16262                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16263                                // App explictly prefers external. Let policy decide
16264                            } else {
16265                                // Prefer previous location
16266                                if (isExternal(installedPkg)) {
16267                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16268                                }
16269                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16270                            }
16271                        }
16272                    } else {
16273                        // Invalid install. Return error code
16274                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16275                    }
16276                }
16277            }
16278            // All the special cases have been taken care of.
16279            // Return result based on recommended install location.
16280            if (onSd) {
16281                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16282            }
16283            return pkgLite.recommendedInstallLocation;
16284        }
16285
16286        /*
16287         * Invoke remote method to get package information and install
16288         * location values. Override install location based on default
16289         * policy if needed and then create install arguments based
16290         * on the install location.
16291         */
16292        public void handleStartCopy() throws RemoteException {
16293            int ret = PackageManager.INSTALL_SUCCEEDED;
16294
16295            // If we're already staged, we've firmly committed to an install location
16296            if (origin.staged) {
16297                if (origin.file != null) {
16298                    installFlags |= PackageManager.INSTALL_INTERNAL;
16299                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16300                } else if (origin.cid != null) {
16301                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16302                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16303                } else {
16304                    throw new IllegalStateException("Invalid stage location");
16305                }
16306            }
16307
16308            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16309            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16310            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16311            PackageInfoLite pkgLite = null;
16312
16313            if (onInt && onSd) {
16314                // Check if both bits are set.
16315                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16316                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16317            } else if (onSd && ephemeral) {
16318                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16319                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16320            } else {
16321                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16322                        packageAbiOverride);
16323
16324                if (DEBUG_EPHEMERAL && ephemeral) {
16325                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16326                }
16327
16328                /*
16329                 * If we have too little free space, try to free cache
16330                 * before giving up.
16331                 */
16332                if (!origin.staged && pkgLite.recommendedInstallLocation
16333                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16334                    // TODO: focus freeing disk space on the target device
16335                    final StorageManager storage = StorageManager.from(mContext);
16336                    final long lowThreshold = storage.getStorageLowBytes(
16337                            Environment.getDataDirectory());
16338
16339                    final long sizeBytes = mContainerService.calculateInstalledSize(
16340                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16341
16342                    try {
16343                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16344                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16345                                installFlags, packageAbiOverride);
16346                    } catch (InstallerException e) {
16347                        Slog.w(TAG, "Failed to free cache", e);
16348                    }
16349
16350                    /*
16351                     * The cache free must have deleted the file we
16352                     * downloaded to install.
16353                     *
16354                     * TODO: fix the "freeCache" call to not delete
16355                     *       the file we care about.
16356                     */
16357                    if (pkgLite.recommendedInstallLocation
16358                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16359                        pkgLite.recommendedInstallLocation
16360                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16361                    }
16362                }
16363            }
16364
16365            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16366                int loc = pkgLite.recommendedInstallLocation;
16367                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16368                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16369                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16370                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16371                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16372                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16373                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16374                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16375                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16376                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16377                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16378                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16379                } else {
16380                    // Override with defaults if needed.
16381                    loc = installLocationPolicy(pkgLite);
16382                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16383                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16384                    } else if (!onSd && !onInt) {
16385                        // Override install location with flags
16386                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16387                            // Set the flag to install on external media.
16388                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16389                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16390                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16391                            if (DEBUG_EPHEMERAL) {
16392                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16393                            }
16394                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16395                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16396                                    |PackageManager.INSTALL_INTERNAL);
16397                        } else {
16398                            // Make sure the flag for installing on external
16399                            // media is unset
16400                            installFlags |= PackageManager.INSTALL_INTERNAL;
16401                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16402                        }
16403                    }
16404                }
16405            }
16406
16407            final InstallArgs args = createInstallArgs(this);
16408            mArgs = args;
16409
16410            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16411                // TODO: http://b/22976637
16412                // Apps installed for "all" users use the device owner to verify the app
16413                UserHandle verifierUser = getUser();
16414                if (verifierUser == UserHandle.ALL) {
16415                    verifierUser = UserHandle.SYSTEM;
16416                }
16417
16418                /*
16419                 * Determine if we have any installed package verifiers. If we
16420                 * do, then we'll defer to them to verify the packages.
16421                 */
16422                final int requiredUid = mRequiredVerifierPackage == null ? -1
16423                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16424                                verifierUser.getIdentifier());
16425                final int installerUid =
16426                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16427                if (!origin.existing && requiredUid != -1
16428                        && isVerificationEnabled(
16429                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16430                    final Intent verification = new Intent(
16431                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16432                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16433                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16434                            PACKAGE_MIME_TYPE);
16435                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16436
16437                    // Query all live verifiers based on current user state
16438                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16439                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16440                            false /*allowDynamicSplits*/);
16441
16442                    if (DEBUG_VERIFY) {
16443                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16444                                + verification.toString() + " with " + pkgLite.verifiers.length
16445                                + " optional verifiers");
16446                    }
16447
16448                    final int verificationId = mPendingVerificationToken++;
16449
16450                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16451
16452                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16453                            installerPackageName);
16454
16455                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16456                            installFlags);
16457
16458                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16459                            pkgLite.packageName);
16460
16461                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16462                            pkgLite.versionCode);
16463
16464                    if (verificationInfo != null) {
16465                        if (verificationInfo.originatingUri != null) {
16466                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16467                                    verificationInfo.originatingUri);
16468                        }
16469                        if (verificationInfo.referrer != null) {
16470                            verification.putExtra(Intent.EXTRA_REFERRER,
16471                                    verificationInfo.referrer);
16472                        }
16473                        if (verificationInfo.originatingUid >= 0) {
16474                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16475                                    verificationInfo.originatingUid);
16476                        }
16477                        if (verificationInfo.installerUid >= 0) {
16478                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16479                                    verificationInfo.installerUid);
16480                        }
16481                    }
16482
16483                    final PackageVerificationState verificationState = new PackageVerificationState(
16484                            requiredUid, args);
16485
16486                    mPendingVerification.append(verificationId, verificationState);
16487
16488                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16489                            receivers, verificationState);
16490
16491                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16492                    final long idleDuration = getVerificationTimeout();
16493
16494                    /*
16495                     * If any sufficient verifiers were listed in the package
16496                     * manifest, attempt to ask them.
16497                     */
16498                    if (sufficientVerifiers != null) {
16499                        final int N = sufficientVerifiers.size();
16500                        if (N == 0) {
16501                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16502                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16503                        } else {
16504                            for (int i = 0; i < N; i++) {
16505                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16506                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16507                                        verifierComponent.getPackageName(), idleDuration,
16508                                        verifierUser.getIdentifier(), false, "package verifier");
16509
16510                                final Intent sufficientIntent = new Intent(verification);
16511                                sufficientIntent.setComponent(verifierComponent);
16512                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16513                            }
16514                        }
16515                    }
16516
16517                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16518                            mRequiredVerifierPackage, receivers);
16519                    if (ret == PackageManager.INSTALL_SUCCEEDED
16520                            && mRequiredVerifierPackage != null) {
16521                        Trace.asyncTraceBegin(
16522                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16523                        /*
16524                         * Send the intent to the required verification agent,
16525                         * but only start the verification timeout after the
16526                         * target BroadcastReceivers have run.
16527                         */
16528                        verification.setComponent(requiredVerifierComponent);
16529                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16530                                mRequiredVerifierPackage, idleDuration,
16531                                verifierUser.getIdentifier(), false, "package verifier");
16532                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16533                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16534                                new BroadcastReceiver() {
16535                                    @Override
16536                                    public void onReceive(Context context, Intent intent) {
16537                                        final Message msg = mHandler
16538                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16539                                        msg.arg1 = verificationId;
16540                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16541                                    }
16542                                }, null, 0, null, null);
16543
16544                        /*
16545                         * We don't want the copy to proceed until verification
16546                         * succeeds, so null out this field.
16547                         */
16548                        mArgs = null;
16549                    }
16550                } else {
16551                    /*
16552                     * No package verification is enabled, so immediately start
16553                     * the remote call to initiate copy using temporary file.
16554                     */
16555                    ret = args.copyApk(mContainerService, true);
16556                }
16557            }
16558
16559            mRet = ret;
16560        }
16561
16562        @Override
16563        void handleReturnCode() {
16564            // If mArgs is null, then MCS couldn't be reached. When it
16565            // reconnects, it will try again to install. At that point, this
16566            // will succeed.
16567            if (mArgs != null) {
16568                processPendingInstall(mArgs, mRet);
16569            }
16570        }
16571
16572        @Override
16573        void handleServiceError() {
16574            mArgs = createInstallArgs(this);
16575            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16576        }
16577
16578        public boolean isForwardLocked() {
16579            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16580        }
16581    }
16582
16583    /**
16584     * Used during creation of InstallArgs
16585     *
16586     * @param installFlags package installation flags
16587     * @return true if should be installed on external storage
16588     */
16589    private static boolean installOnExternalAsec(int installFlags) {
16590        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16591            return false;
16592        }
16593        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16594            return true;
16595        }
16596        return false;
16597    }
16598
16599    /**
16600     * Used during creation of InstallArgs
16601     *
16602     * @param installFlags package installation flags
16603     * @return true if should be installed as forward locked
16604     */
16605    private static boolean installForwardLocked(int installFlags) {
16606        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16607    }
16608
16609    private InstallArgs createInstallArgs(InstallParams params) {
16610        if (params.move != null) {
16611            return new MoveInstallArgs(params);
16612        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16613            return new AsecInstallArgs(params);
16614        } else {
16615            return new FileInstallArgs(params);
16616        }
16617    }
16618
16619    /**
16620     * Create args that describe an existing installed package. Typically used
16621     * when cleaning up old installs, or used as a move source.
16622     */
16623    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16624            String resourcePath, String[] instructionSets) {
16625        final boolean isInAsec;
16626        if (installOnExternalAsec(installFlags)) {
16627            /* Apps on SD card are always in ASEC containers. */
16628            isInAsec = true;
16629        } else if (installForwardLocked(installFlags)
16630                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16631            /*
16632             * Forward-locked apps are only in ASEC containers if they're the
16633             * new style
16634             */
16635            isInAsec = true;
16636        } else {
16637            isInAsec = false;
16638        }
16639
16640        if (isInAsec) {
16641            return new AsecInstallArgs(codePath, instructionSets,
16642                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16643        } else {
16644            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16645        }
16646    }
16647
16648    static abstract class InstallArgs {
16649        /** @see InstallParams#origin */
16650        final OriginInfo origin;
16651        /** @see InstallParams#move */
16652        final MoveInfo move;
16653
16654        final IPackageInstallObserver2 observer;
16655        // Always refers to PackageManager flags only
16656        final int installFlags;
16657        final String installerPackageName;
16658        final String volumeUuid;
16659        final UserHandle user;
16660        final String abiOverride;
16661        final String[] installGrantPermissions;
16662        /** If non-null, drop an async trace when the install completes */
16663        final String traceMethod;
16664        final int traceCookie;
16665        final Certificate[][] certificates;
16666        final int installReason;
16667
16668        // The list of instruction sets supported by this app. This is currently
16669        // only used during the rmdex() phase to clean up resources. We can get rid of this
16670        // if we move dex files under the common app path.
16671        /* nullable */ String[] instructionSets;
16672
16673        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16674                int installFlags, String installerPackageName, String volumeUuid,
16675                UserHandle user, String[] instructionSets,
16676                String abiOverride, String[] installGrantPermissions,
16677                String traceMethod, int traceCookie, Certificate[][] certificates,
16678                int installReason) {
16679            this.origin = origin;
16680            this.move = move;
16681            this.installFlags = installFlags;
16682            this.observer = observer;
16683            this.installerPackageName = installerPackageName;
16684            this.volumeUuid = volumeUuid;
16685            this.user = user;
16686            this.instructionSets = instructionSets;
16687            this.abiOverride = abiOverride;
16688            this.installGrantPermissions = installGrantPermissions;
16689            this.traceMethod = traceMethod;
16690            this.traceCookie = traceCookie;
16691            this.certificates = certificates;
16692            this.installReason = installReason;
16693        }
16694
16695        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16696        abstract int doPreInstall(int status);
16697
16698        /**
16699         * Rename package into final resting place. All paths on the given
16700         * scanned package should be updated to reflect the rename.
16701         */
16702        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16703        abstract int doPostInstall(int status, int uid);
16704
16705        /** @see PackageSettingBase#codePathString */
16706        abstract String getCodePath();
16707        /** @see PackageSettingBase#resourcePathString */
16708        abstract String getResourcePath();
16709
16710        // Need installer lock especially for dex file removal.
16711        abstract void cleanUpResourcesLI();
16712        abstract boolean doPostDeleteLI(boolean delete);
16713
16714        /**
16715         * Called before the source arguments are copied. This is used mostly
16716         * for MoveParams when it needs to read the source file to put it in the
16717         * destination.
16718         */
16719        int doPreCopy() {
16720            return PackageManager.INSTALL_SUCCEEDED;
16721        }
16722
16723        /**
16724         * Called after the source arguments are copied. This is used mostly for
16725         * MoveParams when it needs to read the source file to put it in the
16726         * destination.
16727         */
16728        int doPostCopy(int uid) {
16729            return PackageManager.INSTALL_SUCCEEDED;
16730        }
16731
16732        protected boolean isFwdLocked() {
16733            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16734        }
16735
16736        protected boolean isExternalAsec() {
16737            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16738        }
16739
16740        protected boolean isEphemeral() {
16741            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16742        }
16743
16744        UserHandle getUser() {
16745            return user;
16746        }
16747    }
16748
16749    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16750        if (!allCodePaths.isEmpty()) {
16751            if (instructionSets == null) {
16752                throw new IllegalStateException("instructionSet == null");
16753            }
16754            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16755            for (String codePath : allCodePaths) {
16756                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16757                    try {
16758                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16759                    } catch (InstallerException ignored) {
16760                    }
16761                }
16762            }
16763        }
16764    }
16765
16766    /**
16767     * Logic to handle installation of non-ASEC applications, including copying
16768     * and renaming logic.
16769     */
16770    class FileInstallArgs extends InstallArgs {
16771        private File codeFile;
16772        private File resourceFile;
16773
16774        // Example topology:
16775        // /data/app/com.example/base.apk
16776        // /data/app/com.example/split_foo.apk
16777        // /data/app/com.example/lib/arm/libfoo.so
16778        // /data/app/com.example/lib/arm64/libfoo.so
16779        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16780
16781        /** New install */
16782        FileInstallArgs(InstallParams params) {
16783            super(params.origin, params.move, params.observer, params.installFlags,
16784                    params.installerPackageName, params.volumeUuid,
16785                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16786                    params.grantedRuntimePermissions,
16787                    params.traceMethod, params.traceCookie, params.certificates,
16788                    params.installReason);
16789            if (isFwdLocked()) {
16790                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16791            }
16792        }
16793
16794        /** Existing install */
16795        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16796            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16797                    null, null, null, 0, null /*certificates*/,
16798                    PackageManager.INSTALL_REASON_UNKNOWN);
16799            this.codeFile = (codePath != null) ? new File(codePath) : null;
16800            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16801        }
16802
16803        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16804            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16805            try {
16806                return doCopyApk(imcs, temp);
16807            } finally {
16808                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16809            }
16810        }
16811
16812        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16813            if (origin.staged) {
16814                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16815                codeFile = origin.file;
16816                resourceFile = origin.file;
16817                return PackageManager.INSTALL_SUCCEEDED;
16818            }
16819
16820            try {
16821                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16822                final File tempDir =
16823                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16824                codeFile = tempDir;
16825                resourceFile = tempDir;
16826            } catch (IOException e) {
16827                Slog.w(TAG, "Failed to create copy file: " + e);
16828                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16829            }
16830
16831            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16832                @Override
16833                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16834                    if (!FileUtils.isValidExtFilename(name)) {
16835                        throw new IllegalArgumentException("Invalid filename: " + name);
16836                    }
16837                    try {
16838                        final File file = new File(codeFile, name);
16839                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16840                                O_RDWR | O_CREAT, 0644);
16841                        Os.chmod(file.getAbsolutePath(), 0644);
16842                        return new ParcelFileDescriptor(fd);
16843                    } catch (ErrnoException e) {
16844                        throw new RemoteException("Failed to open: " + e.getMessage());
16845                    }
16846                }
16847            };
16848
16849            int ret = PackageManager.INSTALL_SUCCEEDED;
16850            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16851            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16852                Slog.e(TAG, "Failed to copy package");
16853                return ret;
16854            }
16855
16856            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16857            NativeLibraryHelper.Handle handle = null;
16858            try {
16859                handle = NativeLibraryHelper.Handle.create(codeFile);
16860                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16861                        abiOverride);
16862            } catch (IOException e) {
16863                Slog.e(TAG, "Copying native libraries failed", e);
16864                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16865            } finally {
16866                IoUtils.closeQuietly(handle);
16867            }
16868
16869            return ret;
16870        }
16871
16872        int doPreInstall(int status) {
16873            if (status != PackageManager.INSTALL_SUCCEEDED) {
16874                cleanUp();
16875            }
16876            return status;
16877        }
16878
16879        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16880            if (status != PackageManager.INSTALL_SUCCEEDED) {
16881                cleanUp();
16882                return false;
16883            }
16884
16885            final File targetDir = codeFile.getParentFile();
16886            final File beforeCodeFile = codeFile;
16887            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16888
16889            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16890            try {
16891                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16892            } catch (ErrnoException e) {
16893                Slog.w(TAG, "Failed to rename", e);
16894                return false;
16895            }
16896
16897            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16898                Slog.w(TAG, "Failed to restorecon");
16899                return false;
16900            }
16901
16902            // Reflect the rename internally
16903            codeFile = afterCodeFile;
16904            resourceFile = afterCodeFile;
16905
16906            // Reflect the rename in scanned details
16907            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16908            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16909                    afterCodeFile, pkg.baseCodePath));
16910            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16911                    afterCodeFile, pkg.splitCodePaths));
16912
16913            // Reflect the rename in app info
16914            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16915            pkg.setApplicationInfoCodePath(pkg.codePath);
16916            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16917            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16918            pkg.setApplicationInfoResourcePath(pkg.codePath);
16919            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16920            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16921
16922            return true;
16923        }
16924
16925        int doPostInstall(int status, int uid) {
16926            if (status != PackageManager.INSTALL_SUCCEEDED) {
16927                cleanUp();
16928            }
16929            return status;
16930        }
16931
16932        @Override
16933        String getCodePath() {
16934            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16935        }
16936
16937        @Override
16938        String getResourcePath() {
16939            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16940        }
16941
16942        private boolean cleanUp() {
16943            if (codeFile == null || !codeFile.exists()) {
16944                return false;
16945            }
16946
16947            removeCodePathLI(codeFile);
16948
16949            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16950                resourceFile.delete();
16951            }
16952
16953            return true;
16954        }
16955
16956        void cleanUpResourcesLI() {
16957            // Try enumerating all code paths before deleting
16958            List<String> allCodePaths = Collections.EMPTY_LIST;
16959            if (codeFile != null && codeFile.exists()) {
16960                try {
16961                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16962                    allCodePaths = pkg.getAllCodePaths();
16963                } catch (PackageParserException e) {
16964                    // Ignored; we tried our best
16965                }
16966            }
16967
16968            cleanUp();
16969            removeDexFiles(allCodePaths, instructionSets);
16970        }
16971
16972        boolean doPostDeleteLI(boolean delete) {
16973            // XXX err, shouldn't we respect the delete flag?
16974            cleanUpResourcesLI();
16975            return true;
16976        }
16977    }
16978
16979    private boolean isAsecExternal(String cid) {
16980        final String asecPath = PackageHelper.getSdFilesystem(cid);
16981        return !asecPath.startsWith(mAsecInternalPath);
16982    }
16983
16984    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16985            PackageManagerException {
16986        if (copyRet < 0) {
16987            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16988                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16989                throw new PackageManagerException(copyRet, message);
16990            }
16991        }
16992    }
16993
16994    /**
16995     * Extract the StorageManagerService "container ID" from the full code path of an
16996     * .apk.
16997     */
16998    static String cidFromCodePath(String fullCodePath) {
16999        int eidx = fullCodePath.lastIndexOf("/");
17000        String subStr1 = fullCodePath.substring(0, eidx);
17001        int sidx = subStr1.lastIndexOf("/");
17002        return subStr1.substring(sidx+1, eidx);
17003    }
17004
17005    /**
17006     * Logic to handle installation of ASEC applications, including copying and
17007     * renaming logic.
17008     */
17009    class AsecInstallArgs extends InstallArgs {
17010        static final String RES_FILE_NAME = "pkg.apk";
17011        static final String PUBLIC_RES_FILE_NAME = "res.zip";
17012
17013        String cid;
17014        String packagePath;
17015        String resourcePath;
17016
17017        /** New install */
17018        AsecInstallArgs(InstallParams params) {
17019            super(params.origin, params.move, params.observer, params.installFlags,
17020                    params.installerPackageName, params.volumeUuid,
17021                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17022                    params.grantedRuntimePermissions,
17023                    params.traceMethod, params.traceCookie, params.certificates,
17024                    params.installReason);
17025        }
17026
17027        /** Existing install */
17028        AsecInstallArgs(String fullCodePath, String[] instructionSets,
17029                        boolean isExternal, boolean isForwardLocked) {
17030            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
17031                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17032                    instructionSets, null, null, null, 0, null /*certificates*/,
17033                    PackageManager.INSTALL_REASON_UNKNOWN);
17034            // Hackily pretend we're still looking at a full code path
17035            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
17036                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
17037            }
17038
17039            // Extract cid from fullCodePath
17040            int eidx = fullCodePath.lastIndexOf("/");
17041            String subStr1 = fullCodePath.substring(0, eidx);
17042            int sidx = subStr1.lastIndexOf("/");
17043            cid = subStr1.substring(sidx+1, eidx);
17044            setMountPath(subStr1);
17045        }
17046
17047        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17048            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17049                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17050                    instructionSets, null, null, null, 0, null /*certificates*/,
17051                    PackageManager.INSTALL_REASON_UNKNOWN);
17052            this.cid = cid;
17053            setMountPath(PackageHelper.getSdDir(cid));
17054        }
17055
17056        void createCopyFile() {
17057            cid = mInstallerService.allocateExternalStageCidLegacy();
17058        }
17059
17060        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17061            if (origin.staged && origin.cid != null) {
17062                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17063                cid = origin.cid;
17064                setMountPath(PackageHelper.getSdDir(cid));
17065                return PackageManager.INSTALL_SUCCEEDED;
17066            }
17067
17068            if (temp) {
17069                createCopyFile();
17070            } else {
17071                /*
17072                 * Pre-emptively destroy the container since it's destroyed if
17073                 * copying fails due to it existing anyway.
17074                 */
17075                PackageHelper.destroySdDir(cid);
17076            }
17077
17078            final String newMountPath = imcs.copyPackageToContainer(
17079                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17080                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17081
17082            if (newMountPath != null) {
17083                setMountPath(newMountPath);
17084                return PackageManager.INSTALL_SUCCEEDED;
17085            } else {
17086                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17087            }
17088        }
17089
17090        @Override
17091        String getCodePath() {
17092            return packagePath;
17093        }
17094
17095        @Override
17096        String getResourcePath() {
17097            return resourcePath;
17098        }
17099
17100        int doPreInstall(int status) {
17101            if (status != PackageManager.INSTALL_SUCCEEDED) {
17102                // Destroy container
17103                PackageHelper.destroySdDir(cid);
17104            } else {
17105                boolean mounted = PackageHelper.isContainerMounted(cid);
17106                if (!mounted) {
17107                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17108                            Process.SYSTEM_UID);
17109                    if (newMountPath != null) {
17110                        setMountPath(newMountPath);
17111                    } else {
17112                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17113                    }
17114                }
17115            }
17116            return status;
17117        }
17118
17119        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17120            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17121            String newMountPath = null;
17122            if (PackageHelper.isContainerMounted(cid)) {
17123                // Unmount the container
17124                if (!PackageHelper.unMountSdDir(cid)) {
17125                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17126                    return false;
17127                }
17128            }
17129            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17130                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17131                        " which might be stale. Will try to clean up.");
17132                // Clean up the stale container and proceed to recreate.
17133                if (!PackageHelper.destroySdDir(newCacheId)) {
17134                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17135                    return false;
17136                }
17137                // Successfully cleaned up stale container. Try to rename again.
17138                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17139                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17140                            + " inspite of cleaning it up.");
17141                    return false;
17142                }
17143            }
17144            if (!PackageHelper.isContainerMounted(newCacheId)) {
17145                Slog.w(TAG, "Mounting container " + newCacheId);
17146                newMountPath = PackageHelper.mountSdDir(newCacheId,
17147                        getEncryptKey(), Process.SYSTEM_UID);
17148            } else {
17149                newMountPath = PackageHelper.getSdDir(newCacheId);
17150            }
17151            if (newMountPath == null) {
17152                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17153                return false;
17154            }
17155            Log.i(TAG, "Succesfully renamed " + cid +
17156                    " to " + newCacheId +
17157                    " at new path: " + newMountPath);
17158            cid = newCacheId;
17159
17160            final File beforeCodeFile = new File(packagePath);
17161            setMountPath(newMountPath);
17162            final File afterCodeFile = new File(packagePath);
17163
17164            // Reflect the rename in scanned details
17165            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17166            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17167                    afterCodeFile, pkg.baseCodePath));
17168            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17169                    afterCodeFile, pkg.splitCodePaths));
17170
17171            // Reflect the rename in app info
17172            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17173            pkg.setApplicationInfoCodePath(pkg.codePath);
17174            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17175            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17176            pkg.setApplicationInfoResourcePath(pkg.codePath);
17177            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17178            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17179
17180            return true;
17181        }
17182
17183        private void setMountPath(String mountPath) {
17184            final File mountFile = new File(mountPath);
17185
17186            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17187            if (monolithicFile.exists()) {
17188                packagePath = monolithicFile.getAbsolutePath();
17189                if (isFwdLocked()) {
17190                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17191                } else {
17192                    resourcePath = packagePath;
17193                }
17194            } else {
17195                packagePath = mountFile.getAbsolutePath();
17196                resourcePath = packagePath;
17197            }
17198        }
17199
17200        int doPostInstall(int status, int uid) {
17201            if (status != PackageManager.INSTALL_SUCCEEDED) {
17202                cleanUp();
17203            } else {
17204                final int groupOwner;
17205                final String protectedFile;
17206                if (isFwdLocked()) {
17207                    groupOwner = UserHandle.getSharedAppGid(uid);
17208                    protectedFile = RES_FILE_NAME;
17209                } else {
17210                    groupOwner = -1;
17211                    protectedFile = null;
17212                }
17213
17214                if (uid < Process.FIRST_APPLICATION_UID
17215                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17216                    Slog.e(TAG, "Failed to finalize " + cid);
17217                    PackageHelper.destroySdDir(cid);
17218                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17219                }
17220
17221                boolean mounted = PackageHelper.isContainerMounted(cid);
17222                if (!mounted) {
17223                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17224                }
17225            }
17226            return status;
17227        }
17228
17229        private void cleanUp() {
17230            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17231
17232            // Destroy secure container
17233            PackageHelper.destroySdDir(cid);
17234        }
17235
17236        private List<String> getAllCodePaths() {
17237            final File codeFile = new File(getCodePath());
17238            if (codeFile != null && codeFile.exists()) {
17239                try {
17240                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17241                    return pkg.getAllCodePaths();
17242                } catch (PackageParserException e) {
17243                    // Ignored; we tried our best
17244                }
17245            }
17246            return Collections.EMPTY_LIST;
17247        }
17248
17249        void cleanUpResourcesLI() {
17250            // Enumerate all code paths before deleting
17251            cleanUpResourcesLI(getAllCodePaths());
17252        }
17253
17254        private void cleanUpResourcesLI(List<String> allCodePaths) {
17255            cleanUp();
17256            removeDexFiles(allCodePaths, instructionSets);
17257        }
17258
17259        String getPackageName() {
17260            return getAsecPackageName(cid);
17261        }
17262
17263        boolean doPostDeleteLI(boolean delete) {
17264            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17265            final List<String> allCodePaths = getAllCodePaths();
17266            boolean mounted = PackageHelper.isContainerMounted(cid);
17267            if (mounted) {
17268                // Unmount first
17269                if (PackageHelper.unMountSdDir(cid)) {
17270                    mounted = false;
17271                }
17272            }
17273            if (!mounted && delete) {
17274                cleanUpResourcesLI(allCodePaths);
17275            }
17276            return !mounted;
17277        }
17278
17279        @Override
17280        int doPreCopy() {
17281            if (isFwdLocked()) {
17282                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17283                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17284                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17285                }
17286            }
17287
17288            return PackageManager.INSTALL_SUCCEEDED;
17289        }
17290
17291        @Override
17292        int doPostCopy(int uid) {
17293            if (isFwdLocked()) {
17294                if (uid < Process.FIRST_APPLICATION_UID
17295                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17296                                RES_FILE_NAME)) {
17297                    Slog.e(TAG, "Failed to finalize " + cid);
17298                    PackageHelper.destroySdDir(cid);
17299                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17300                }
17301            }
17302
17303            return PackageManager.INSTALL_SUCCEEDED;
17304        }
17305    }
17306
17307    /**
17308     * Logic to handle movement of existing installed applications.
17309     */
17310    class MoveInstallArgs extends InstallArgs {
17311        private File codeFile;
17312        private File resourceFile;
17313
17314        /** New install */
17315        MoveInstallArgs(InstallParams params) {
17316            super(params.origin, params.move, params.observer, params.installFlags,
17317                    params.installerPackageName, params.volumeUuid,
17318                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17319                    params.grantedRuntimePermissions,
17320                    params.traceMethod, params.traceCookie, params.certificates,
17321                    params.installReason);
17322        }
17323
17324        int copyApk(IMediaContainerService imcs, boolean temp) {
17325            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17326                    + move.fromUuid + " to " + move.toUuid);
17327            synchronized (mInstaller) {
17328                try {
17329                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17330                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17331                } catch (InstallerException e) {
17332                    Slog.w(TAG, "Failed to move app", e);
17333                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17334                }
17335            }
17336
17337            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17338            resourceFile = codeFile;
17339            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17340
17341            return PackageManager.INSTALL_SUCCEEDED;
17342        }
17343
17344        int doPreInstall(int status) {
17345            if (status != PackageManager.INSTALL_SUCCEEDED) {
17346                cleanUp(move.toUuid);
17347            }
17348            return status;
17349        }
17350
17351        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17352            if (status != PackageManager.INSTALL_SUCCEEDED) {
17353                cleanUp(move.toUuid);
17354                return false;
17355            }
17356
17357            // Reflect the move in app info
17358            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17359            pkg.setApplicationInfoCodePath(pkg.codePath);
17360            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17361            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17362            pkg.setApplicationInfoResourcePath(pkg.codePath);
17363            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17364            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17365
17366            return true;
17367        }
17368
17369        int doPostInstall(int status, int uid) {
17370            if (status == PackageManager.INSTALL_SUCCEEDED) {
17371                cleanUp(move.fromUuid);
17372            } else {
17373                cleanUp(move.toUuid);
17374            }
17375            return status;
17376        }
17377
17378        @Override
17379        String getCodePath() {
17380            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17381        }
17382
17383        @Override
17384        String getResourcePath() {
17385            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17386        }
17387
17388        private boolean cleanUp(String volumeUuid) {
17389            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17390                    move.dataAppName);
17391            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17392            final int[] userIds = sUserManager.getUserIds();
17393            synchronized (mInstallLock) {
17394                // Clean up both app data and code
17395                // All package moves are frozen until finished
17396                for (int userId : userIds) {
17397                    try {
17398                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17399                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17400                    } catch (InstallerException e) {
17401                        Slog.w(TAG, String.valueOf(e));
17402                    }
17403                }
17404                removeCodePathLI(codeFile);
17405            }
17406            return true;
17407        }
17408
17409        void cleanUpResourcesLI() {
17410            throw new UnsupportedOperationException();
17411        }
17412
17413        boolean doPostDeleteLI(boolean delete) {
17414            throw new UnsupportedOperationException();
17415        }
17416    }
17417
17418    static String getAsecPackageName(String packageCid) {
17419        int idx = packageCid.lastIndexOf("-");
17420        if (idx == -1) {
17421            return packageCid;
17422        }
17423        return packageCid.substring(0, idx);
17424    }
17425
17426    // Utility method used to create code paths based on package name and available index.
17427    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17428        String idxStr = "";
17429        int idx = 1;
17430        // Fall back to default value of idx=1 if prefix is not
17431        // part of oldCodePath
17432        if (oldCodePath != null) {
17433            String subStr = oldCodePath;
17434            // Drop the suffix right away
17435            if (suffix != null && subStr.endsWith(suffix)) {
17436                subStr = subStr.substring(0, subStr.length() - suffix.length());
17437            }
17438            // If oldCodePath already contains prefix find out the
17439            // ending index to either increment or decrement.
17440            int sidx = subStr.lastIndexOf(prefix);
17441            if (sidx != -1) {
17442                subStr = subStr.substring(sidx + prefix.length());
17443                if (subStr != null) {
17444                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17445                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17446                    }
17447                    try {
17448                        idx = Integer.parseInt(subStr);
17449                        if (idx <= 1) {
17450                            idx++;
17451                        } else {
17452                            idx--;
17453                        }
17454                    } catch(NumberFormatException e) {
17455                    }
17456                }
17457            }
17458        }
17459        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17460        return prefix + idxStr;
17461    }
17462
17463    private File getNextCodePath(File targetDir, String packageName) {
17464        File result;
17465        SecureRandom random = new SecureRandom();
17466        byte[] bytes = new byte[16];
17467        do {
17468            random.nextBytes(bytes);
17469            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17470            result = new File(targetDir, packageName + "-" + suffix);
17471        } while (result.exists());
17472        return result;
17473    }
17474
17475    // Utility method that returns the relative package path with respect
17476    // to the installation directory. Like say for /data/data/com.test-1.apk
17477    // string com.test-1 is returned.
17478    static String deriveCodePathName(String codePath) {
17479        if (codePath == null) {
17480            return null;
17481        }
17482        final File codeFile = new File(codePath);
17483        final String name = codeFile.getName();
17484        if (codeFile.isDirectory()) {
17485            return name;
17486        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17487            final int lastDot = name.lastIndexOf('.');
17488            return name.substring(0, lastDot);
17489        } else {
17490            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17491            return null;
17492        }
17493    }
17494
17495    static class PackageInstalledInfo {
17496        String name;
17497        int uid;
17498        // The set of users that originally had this package installed.
17499        int[] origUsers;
17500        // The set of users that now have this package installed.
17501        int[] newUsers;
17502        PackageParser.Package pkg;
17503        int returnCode;
17504        String returnMsg;
17505        String installerPackageName;
17506        PackageRemovedInfo removedInfo;
17507        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17508
17509        public void setError(int code, String msg) {
17510            setReturnCode(code);
17511            setReturnMessage(msg);
17512            Slog.w(TAG, msg);
17513        }
17514
17515        public void setError(String msg, PackageParserException e) {
17516            setReturnCode(e.error);
17517            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17518            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17519            for (int i = 0; i < childCount; i++) {
17520                addedChildPackages.valueAt(i).setError(msg, e);
17521            }
17522            Slog.w(TAG, msg, e);
17523        }
17524
17525        public void setError(String msg, PackageManagerException e) {
17526            returnCode = e.error;
17527            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17528            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17529            for (int i = 0; i < childCount; i++) {
17530                addedChildPackages.valueAt(i).setError(msg, e);
17531            }
17532            Slog.w(TAG, msg, e);
17533        }
17534
17535        public void setReturnCode(int returnCode) {
17536            this.returnCode = returnCode;
17537            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17538            for (int i = 0; i < childCount; i++) {
17539                addedChildPackages.valueAt(i).returnCode = returnCode;
17540            }
17541        }
17542
17543        private void setReturnMessage(String returnMsg) {
17544            this.returnMsg = returnMsg;
17545            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17546            for (int i = 0; i < childCount; i++) {
17547                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17548            }
17549        }
17550
17551        // In some error cases we want to convey more info back to the observer
17552        String origPackage;
17553        String origPermission;
17554    }
17555
17556    /*
17557     * Install a non-existing package.
17558     */
17559    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17560            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17561            PackageInstalledInfo res, int installReason) {
17562        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17563
17564        // Remember this for later, in case we need to rollback this install
17565        String pkgName = pkg.packageName;
17566
17567        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17568
17569        synchronized(mPackages) {
17570            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17571            if (renamedPackage != null) {
17572                // A package with the same name is already installed, though
17573                // it has been renamed to an older name.  The package we
17574                // are trying to install should be installed as an update to
17575                // the existing one, but that has not been requested, so bail.
17576                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17577                        + " without first uninstalling package running as "
17578                        + renamedPackage);
17579                return;
17580            }
17581            if (mPackages.containsKey(pkgName)) {
17582                // Don't allow installation over an existing package with the same name.
17583                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17584                        + " without first uninstalling.");
17585                return;
17586            }
17587        }
17588
17589        try {
17590            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17591                    System.currentTimeMillis(), user);
17592
17593            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17594
17595            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17596                prepareAppDataAfterInstallLIF(newPackage);
17597
17598            } else {
17599                // Remove package from internal structures, but keep around any
17600                // data that might have already existed
17601                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17602                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17603            }
17604        } catch (PackageManagerException e) {
17605            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17606        }
17607
17608        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17609    }
17610
17611    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17612        // Can't rotate keys during boot or if sharedUser.
17613        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17614                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17615            return false;
17616        }
17617        // app is using upgradeKeySets; make sure all are valid
17618        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17619        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17620        for (int i = 0; i < upgradeKeySets.length; i++) {
17621            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17622                Slog.wtf(TAG, "Package "
17623                         + (oldPs.name != null ? oldPs.name : "<null>")
17624                         + " contains upgrade-key-set reference to unknown key-set: "
17625                         + upgradeKeySets[i]
17626                         + " reverting to signatures check.");
17627                return false;
17628            }
17629        }
17630        return true;
17631    }
17632
17633    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17634        // Upgrade keysets are being used.  Determine if new package has a superset of the
17635        // required keys.
17636        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17637        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17638        for (int i = 0; i < upgradeKeySets.length; i++) {
17639            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17640            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17641                return true;
17642            }
17643        }
17644        return false;
17645    }
17646
17647    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17648        try (DigestInputStream digestStream =
17649                new DigestInputStream(new FileInputStream(file), digest)) {
17650            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17651        }
17652    }
17653
17654    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17655            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17656            int installReason) {
17657        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17658
17659        final PackageParser.Package oldPackage;
17660        final PackageSetting ps;
17661        final String pkgName = pkg.packageName;
17662        final int[] allUsers;
17663        final int[] installedUsers;
17664
17665        synchronized(mPackages) {
17666            oldPackage = mPackages.get(pkgName);
17667            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17668
17669            // don't allow upgrade to target a release SDK from a pre-release SDK
17670            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17671                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17672            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17673                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17674            if (oldTargetsPreRelease
17675                    && !newTargetsPreRelease
17676                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17677                Slog.w(TAG, "Can't install package targeting released sdk");
17678                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17679                return;
17680            }
17681
17682            ps = mSettings.mPackages.get(pkgName);
17683
17684            // verify signatures are valid
17685            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17686                if (!checkUpgradeKeySetLP(ps, pkg)) {
17687                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17688                            "New package not signed by keys specified by upgrade-keysets: "
17689                                    + pkgName);
17690                    return;
17691                }
17692            } else {
17693                // default to original signature matching
17694                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17695                        != PackageManager.SIGNATURE_MATCH) {
17696                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17697                            "New package has a different signature: " + pkgName);
17698                    return;
17699                }
17700            }
17701
17702            // don't allow a system upgrade unless the upgrade hash matches
17703            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17704                byte[] digestBytes = null;
17705                try {
17706                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17707                    updateDigest(digest, new File(pkg.baseCodePath));
17708                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17709                        for (String path : pkg.splitCodePaths) {
17710                            updateDigest(digest, new File(path));
17711                        }
17712                    }
17713                    digestBytes = digest.digest();
17714                } catch (NoSuchAlgorithmException | IOException e) {
17715                    res.setError(INSTALL_FAILED_INVALID_APK,
17716                            "Could not compute hash: " + pkgName);
17717                    return;
17718                }
17719                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17720                    res.setError(INSTALL_FAILED_INVALID_APK,
17721                            "New package fails restrict-update check: " + pkgName);
17722                    return;
17723                }
17724                // retain upgrade restriction
17725                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17726            }
17727
17728            // Check for shared user id changes
17729            String invalidPackageName =
17730                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17731            if (invalidPackageName != null) {
17732                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17733                        "Package " + invalidPackageName + " tried to change user "
17734                                + oldPackage.mSharedUserId);
17735                return;
17736            }
17737
17738            // In case of rollback, remember per-user/profile install state
17739            allUsers = sUserManager.getUserIds();
17740            installedUsers = ps.queryInstalledUsers(allUsers, true);
17741
17742            // don't allow an upgrade from full to ephemeral
17743            if (isInstantApp) {
17744                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17745                    for (int currentUser : allUsers) {
17746                        if (!ps.getInstantApp(currentUser)) {
17747                            // can't downgrade from full to instant
17748                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17749                                    + " for user: " + currentUser);
17750                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17751                            return;
17752                        }
17753                    }
17754                } else if (!ps.getInstantApp(user.getIdentifier())) {
17755                    // can't downgrade from full to instant
17756                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17757                            + " for user: " + user.getIdentifier());
17758                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17759                    return;
17760                }
17761            }
17762        }
17763
17764        // Update what is removed
17765        res.removedInfo = new PackageRemovedInfo(this);
17766        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17767        res.removedInfo.removedPackage = oldPackage.packageName;
17768        res.removedInfo.installerPackageName = ps.installerPackageName;
17769        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17770        res.removedInfo.isUpdate = true;
17771        res.removedInfo.origUsers = installedUsers;
17772        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17773        for (int i = 0; i < installedUsers.length; i++) {
17774            final int userId = installedUsers[i];
17775            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17776        }
17777
17778        final int childCount = (oldPackage.childPackages != null)
17779                ? oldPackage.childPackages.size() : 0;
17780        for (int i = 0; i < childCount; i++) {
17781            boolean childPackageUpdated = false;
17782            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17783            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17784            if (res.addedChildPackages != null) {
17785                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17786                if (childRes != null) {
17787                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17788                    childRes.removedInfo.removedPackage = childPkg.packageName;
17789                    if (childPs != null) {
17790                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17791                    }
17792                    childRes.removedInfo.isUpdate = true;
17793                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17794                    childPackageUpdated = true;
17795                }
17796            }
17797            if (!childPackageUpdated) {
17798                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17799                childRemovedRes.removedPackage = childPkg.packageName;
17800                if (childPs != null) {
17801                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17802                }
17803                childRemovedRes.isUpdate = false;
17804                childRemovedRes.dataRemoved = true;
17805                synchronized (mPackages) {
17806                    if (childPs != null) {
17807                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17808                    }
17809                }
17810                if (res.removedInfo.removedChildPackages == null) {
17811                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17812                }
17813                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17814            }
17815        }
17816
17817        boolean sysPkg = (isSystemApp(oldPackage));
17818        if (sysPkg) {
17819            // Set the system/privileged/oem flags as needed
17820            final boolean privileged =
17821                    (oldPackage.applicationInfo.privateFlags
17822                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17823            final boolean oem =
17824                    (oldPackage.applicationInfo.privateFlags
17825                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17826            final int systemPolicyFlags = policyFlags
17827                    | PackageParser.PARSE_IS_SYSTEM
17828                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
17829                    | (oem ? PARSE_IS_OEM : 0);
17830
17831            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17832                    user, allUsers, installerPackageName, res, installReason);
17833        } else {
17834            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17835                    user, allUsers, installerPackageName, res, installReason);
17836        }
17837    }
17838
17839    @Override
17840    public List<String> getPreviousCodePaths(String packageName) {
17841        final int callingUid = Binder.getCallingUid();
17842        final List<String> result = new ArrayList<>();
17843        if (getInstantAppPackageName(callingUid) != null) {
17844            return result;
17845        }
17846        final PackageSetting ps = mSettings.mPackages.get(packageName);
17847        if (ps != null
17848                && ps.oldCodePaths != null
17849                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17850            result.addAll(ps.oldCodePaths);
17851        }
17852        return result;
17853    }
17854
17855    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17856            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17857            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17858            int installReason) {
17859        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17860                + deletedPackage);
17861
17862        String pkgName = deletedPackage.packageName;
17863        boolean deletedPkg = true;
17864        boolean addedPkg = false;
17865        boolean updatedSettings = false;
17866        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17867        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17868                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17869
17870        final long origUpdateTime = (pkg.mExtras != null)
17871                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17872
17873        // First delete the existing package while retaining the data directory
17874        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17875                res.removedInfo, true, pkg)) {
17876            // If the existing package wasn't successfully deleted
17877            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17878            deletedPkg = false;
17879        } else {
17880            // Successfully deleted the old package; proceed with replace.
17881
17882            // If deleted package lived in a container, give users a chance to
17883            // relinquish resources before killing.
17884            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17885                if (DEBUG_INSTALL) {
17886                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17887                }
17888                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17889                final ArrayList<String> pkgList = new ArrayList<String>(1);
17890                pkgList.add(deletedPackage.applicationInfo.packageName);
17891                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17892            }
17893
17894            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17895                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17896            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17897
17898            try {
17899                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17900                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17901                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17902                        installReason);
17903
17904                // Update the in-memory copy of the previous code paths.
17905                PackageSetting ps = mSettings.mPackages.get(pkgName);
17906                if (!killApp) {
17907                    if (ps.oldCodePaths == null) {
17908                        ps.oldCodePaths = new ArraySet<>();
17909                    }
17910                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17911                    if (deletedPackage.splitCodePaths != null) {
17912                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17913                    }
17914                } else {
17915                    ps.oldCodePaths = null;
17916                }
17917                if (ps.childPackageNames != null) {
17918                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17919                        final String childPkgName = ps.childPackageNames.get(i);
17920                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17921                        childPs.oldCodePaths = ps.oldCodePaths;
17922                    }
17923                }
17924                // set instant app status, but, only if it's explicitly specified
17925                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17926                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17927                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17928                prepareAppDataAfterInstallLIF(newPackage);
17929                addedPkg = true;
17930                mDexManager.notifyPackageUpdated(newPackage.packageName,
17931                        newPackage.baseCodePath, newPackage.splitCodePaths);
17932            } catch (PackageManagerException e) {
17933                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17934            }
17935        }
17936
17937        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17938            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17939
17940            // Revert all internal state mutations and added folders for the failed install
17941            if (addedPkg) {
17942                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17943                        res.removedInfo, true, null);
17944            }
17945
17946            // Restore the old package
17947            if (deletedPkg) {
17948                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17949                File restoreFile = new File(deletedPackage.codePath);
17950                // Parse old package
17951                boolean oldExternal = isExternal(deletedPackage);
17952                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17953                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17954                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17955                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17956                try {
17957                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17958                            null);
17959                } catch (PackageManagerException e) {
17960                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17961                            + e.getMessage());
17962                    return;
17963                }
17964
17965                synchronized (mPackages) {
17966                    // Ensure the installer package name up to date
17967                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17968
17969                    // Update permissions for restored package
17970                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17971
17972                    mSettings.writeLPr();
17973                }
17974
17975                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17976            }
17977        } else {
17978            synchronized (mPackages) {
17979                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17980                if (ps != null) {
17981                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17982                    if (res.removedInfo.removedChildPackages != null) {
17983                        final int childCount = res.removedInfo.removedChildPackages.size();
17984                        // Iterate in reverse as we may modify the collection
17985                        for (int i = childCount - 1; i >= 0; i--) {
17986                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17987                            if (res.addedChildPackages.containsKey(childPackageName)) {
17988                                res.removedInfo.removedChildPackages.removeAt(i);
17989                            } else {
17990                                PackageRemovedInfo childInfo = res.removedInfo
17991                                        .removedChildPackages.valueAt(i);
17992                                childInfo.removedForAllUsers = mPackages.get(
17993                                        childInfo.removedPackage) == null;
17994                            }
17995                        }
17996                    }
17997                }
17998            }
17999        }
18000    }
18001
18002    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
18003            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
18004            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
18005            int installReason) {
18006        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
18007                + ", old=" + deletedPackage);
18008
18009        final boolean disabledSystem;
18010
18011        // Remove existing system package
18012        removePackageLI(deletedPackage, true);
18013
18014        synchronized (mPackages) {
18015            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
18016        }
18017        if (!disabledSystem) {
18018            // We didn't need to disable the .apk as a current system package,
18019            // which means we are replacing another update that is already
18020            // installed.  We need to make sure to delete the older one's .apk.
18021            res.removedInfo.args = createInstallArgsForExisting(0,
18022                    deletedPackage.applicationInfo.getCodePath(),
18023                    deletedPackage.applicationInfo.getResourcePath(),
18024                    getAppDexInstructionSets(deletedPackage.applicationInfo));
18025        } else {
18026            res.removedInfo.args = null;
18027        }
18028
18029        // Successfully disabled the old package. Now proceed with re-installation
18030        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
18031                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18032        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
18033
18034        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18035        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
18036                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
18037
18038        PackageParser.Package newPackage = null;
18039        try {
18040            // Add the package to the internal data structures
18041            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
18042
18043            // Set the update and install times
18044            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
18045            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18046                    System.currentTimeMillis());
18047
18048            // Update the package dynamic state if succeeded
18049            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18050                // Now that the install succeeded make sure we remove data
18051                // directories for any child package the update removed.
18052                final int deletedChildCount = (deletedPackage.childPackages != null)
18053                        ? deletedPackage.childPackages.size() : 0;
18054                final int newChildCount = (newPackage.childPackages != null)
18055                        ? newPackage.childPackages.size() : 0;
18056                for (int i = 0; i < deletedChildCount; i++) {
18057                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18058                    boolean childPackageDeleted = true;
18059                    for (int j = 0; j < newChildCount; j++) {
18060                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18061                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18062                            childPackageDeleted = false;
18063                            break;
18064                        }
18065                    }
18066                    if (childPackageDeleted) {
18067                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18068                                deletedChildPkg.packageName);
18069                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18070                            PackageRemovedInfo removedChildRes = res.removedInfo
18071                                    .removedChildPackages.get(deletedChildPkg.packageName);
18072                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18073                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18074                        }
18075                    }
18076                }
18077
18078                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18079                        installReason);
18080                prepareAppDataAfterInstallLIF(newPackage);
18081
18082                mDexManager.notifyPackageUpdated(newPackage.packageName,
18083                            newPackage.baseCodePath, newPackage.splitCodePaths);
18084            }
18085        } catch (PackageManagerException e) {
18086            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18087            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18088        }
18089
18090        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18091            // Re installation failed. Restore old information
18092            // Remove new pkg information
18093            if (newPackage != null) {
18094                removeInstalledPackageLI(newPackage, true);
18095            }
18096            // Add back the old system package
18097            try {
18098                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18099            } catch (PackageManagerException e) {
18100                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18101            }
18102
18103            synchronized (mPackages) {
18104                if (disabledSystem) {
18105                    enableSystemPackageLPw(deletedPackage);
18106                }
18107
18108                // Ensure the installer package name up to date
18109                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18110
18111                // Update permissions for restored package
18112                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18113
18114                mSettings.writeLPr();
18115            }
18116
18117            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18118                    + " after failed upgrade");
18119        }
18120    }
18121
18122    /**
18123     * Checks whether the parent or any of the child packages have a change shared
18124     * user. For a package to be a valid update the shred users of the parent and
18125     * the children should match. We may later support changing child shared users.
18126     * @param oldPkg The updated package.
18127     * @param newPkg The update package.
18128     * @return The shared user that change between the versions.
18129     */
18130    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18131            PackageParser.Package newPkg) {
18132        // Check parent shared user
18133        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18134            return newPkg.packageName;
18135        }
18136        // Check child shared users
18137        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18138        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18139        for (int i = 0; i < newChildCount; i++) {
18140            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18141            // If this child was present, did it have the same shared user?
18142            for (int j = 0; j < oldChildCount; j++) {
18143                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18144                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18145                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18146                    return newChildPkg.packageName;
18147                }
18148            }
18149        }
18150        return null;
18151    }
18152
18153    private void removeNativeBinariesLI(PackageSetting ps) {
18154        // Remove the lib path for the parent package
18155        if (ps != null) {
18156            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18157            // Remove the lib path for the child packages
18158            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18159            for (int i = 0; i < childCount; i++) {
18160                PackageSetting childPs = null;
18161                synchronized (mPackages) {
18162                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18163                }
18164                if (childPs != null) {
18165                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18166                            .legacyNativeLibraryPathString);
18167                }
18168            }
18169        }
18170    }
18171
18172    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18173        // Enable the parent package
18174        mSettings.enableSystemPackageLPw(pkg.packageName);
18175        // Enable the child packages
18176        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18177        for (int i = 0; i < childCount; i++) {
18178            PackageParser.Package childPkg = pkg.childPackages.get(i);
18179            mSettings.enableSystemPackageLPw(childPkg.packageName);
18180        }
18181    }
18182
18183    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18184            PackageParser.Package newPkg) {
18185        // Disable the parent package (parent always replaced)
18186        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18187        // Disable the child packages
18188        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18189        for (int i = 0; i < childCount; i++) {
18190            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18191            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18192            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18193        }
18194        return disabled;
18195    }
18196
18197    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18198            String installerPackageName) {
18199        // Enable the parent package
18200        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18201        // Enable the child packages
18202        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18203        for (int i = 0; i < childCount; i++) {
18204            PackageParser.Package childPkg = pkg.childPackages.get(i);
18205            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18206        }
18207    }
18208
18209    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18210        // Collect all used permissions in the UID
18211        ArraySet<String> usedPermissions = new ArraySet<>();
18212        final int packageCount = su.packages.size();
18213        for (int i = 0; i < packageCount; i++) {
18214            PackageSetting ps = su.packages.valueAt(i);
18215            if (ps.pkg == null) {
18216                continue;
18217            }
18218            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18219            for (int j = 0; j < requestedPermCount; j++) {
18220                String permission = ps.pkg.requestedPermissions.get(j);
18221                BasePermission bp = mSettings.mPermissions.get(permission);
18222                if (bp != null) {
18223                    usedPermissions.add(permission);
18224                }
18225            }
18226        }
18227
18228        PermissionsState permissionsState = su.getPermissionsState();
18229        // Prune install permissions
18230        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18231        final int installPermCount = installPermStates.size();
18232        for (int i = installPermCount - 1; i >= 0;  i--) {
18233            PermissionState permissionState = installPermStates.get(i);
18234            if (!usedPermissions.contains(permissionState.getName())) {
18235                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18236                if (bp != null) {
18237                    permissionsState.revokeInstallPermission(bp);
18238                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18239                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18240                }
18241            }
18242        }
18243
18244        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18245
18246        // Prune runtime permissions
18247        for (int userId : allUserIds) {
18248            List<PermissionState> runtimePermStates = permissionsState
18249                    .getRuntimePermissionStates(userId);
18250            final int runtimePermCount = runtimePermStates.size();
18251            for (int i = runtimePermCount - 1; i >= 0; i--) {
18252                PermissionState permissionState = runtimePermStates.get(i);
18253                if (!usedPermissions.contains(permissionState.getName())) {
18254                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18255                    if (bp != null) {
18256                        permissionsState.revokeRuntimePermission(bp, userId);
18257                        permissionsState.updatePermissionFlags(bp, userId,
18258                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18259                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18260                                runtimePermissionChangedUserIds, userId);
18261                    }
18262                }
18263            }
18264        }
18265
18266        return runtimePermissionChangedUserIds;
18267    }
18268
18269    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18270            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18271        // Update the parent package setting
18272        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18273                res, user, installReason);
18274        // Update the child packages setting
18275        final int childCount = (newPackage.childPackages != null)
18276                ? newPackage.childPackages.size() : 0;
18277        for (int i = 0; i < childCount; i++) {
18278            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18279            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18280            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18281                    childRes.origUsers, childRes, user, installReason);
18282        }
18283    }
18284
18285    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18286            String installerPackageName, int[] allUsers, int[] installedForUsers,
18287            PackageInstalledInfo res, UserHandle user, int installReason) {
18288        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18289
18290        String pkgName = newPackage.packageName;
18291        synchronized (mPackages) {
18292            //write settings. the installStatus will be incomplete at this stage.
18293            //note that the new package setting would have already been
18294            //added to mPackages. It hasn't been persisted yet.
18295            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18296            // TODO: Remove this write? It's also written at the end of this method
18297            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18298            mSettings.writeLPr();
18299            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18300        }
18301
18302        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18303        synchronized (mPackages) {
18304            updatePermissionsLPw(newPackage.packageName, newPackage,
18305                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18306                            ? UPDATE_PERMISSIONS_ALL : 0));
18307            // For system-bundled packages, we assume that installing an upgraded version
18308            // of the package implies that the user actually wants to run that new code,
18309            // so we enable the package.
18310            PackageSetting ps = mSettings.mPackages.get(pkgName);
18311            final int userId = user.getIdentifier();
18312            if (ps != null) {
18313                if (isSystemApp(newPackage)) {
18314                    if (DEBUG_INSTALL) {
18315                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18316                    }
18317                    // Enable system package for requested users
18318                    if (res.origUsers != null) {
18319                        for (int origUserId : res.origUsers) {
18320                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18321                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18322                                        origUserId, installerPackageName);
18323                            }
18324                        }
18325                    }
18326                    // Also convey the prior install/uninstall state
18327                    if (allUsers != null && installedForUsers != null) {
18328                        for (int currentUserId : allUsers) {
18329                            final boolean installed = ArrayUtils.contains(
18330                                    installedForUsers, currentUserId);
18331                            if (DEBUG_INSTALL) {
18332                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18333                            }
18334                            ps.setInstalled(installed, currentUserId);
18335                        }
18336                        // these install state changes will be persisted in the
18337                        // upcoming call to mSettings.writeLPr().
18338                    }
18339                }
18340                // It's implied that when a user requests installation, they want the app to be
18341                // installed and enabled.
18342                if (userId != UserHandle.USER_ALL) {
18343                    ps.setInstalled(true, userId);
18344                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18345                }
18346
18347                // When replacing an existing package, preserve the original install reason for all
18348                // users that had the package installed before.
18349                final Set<Integer> previousUserIds = new ArraySet<>();
18350                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18351                    final int installReasonCount = res.removedInfo.installReasons.size();
18352                    for (int i = 0; i < installReasonCount; i++) {
18353                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18354                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18355                        ps.setInstallReason(previousInstallReason, previousUserId);
18356                        previousUserIds.add(previousUserId);
18357                    }
18358                }
18359
18360                // Set install reason for users that are having the package newly installed.
18361                if (userId == UserHandle.USER_ALL) {
18362                    for (int currentUserId : sUserManager.getUserIds()) {
18363                        if (!previousUserIds.contains(currentUserId)) {
18364                            ps.setInstallReason(installReason, currentUserId);
18365                        }
18366                    }
18367                } else if (!previousUserIds.contains(userId)) {
18368                    ps.setInstallReason(installReason, userId);
18369                }
18370                mSettings.writeKernelMappingLPr(ps);
18371            }
18372            res.name = pkgName;
18373            res.uid = newPackage.applicationInfo.uid;
18374            res.pkg = newPackage;
18375            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18376            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18377            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18378            //to update install status
18379            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18380            mSettings.writeLPr();
18381            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18382        }
18383
18384        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18385    }
18386
18387    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18388        try {
18389            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18390            installPackageLI(args, res);
18391        } finally {
18392            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18393        }
18394    }
18395
18396    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18397        final int installFlags = args.installFlags;
18398        final String installerPackageName = args.installerPackageName;
18399        final String volumeUuid = args.volumeUuid;
18400        final File tmpPackageFile = new File(args.getCodePath());
18401        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18402        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18403                || (args.volumeUuid != null));
18404        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18405        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18406        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18407        final boolean virtualPreload =
18408                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18409        boolean replace = false;
18410        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18411        if (args.move != null) {
18412            // moving a complete application; perform an initial scan on the new install location
18413            scanFlags |= SCAN_INITIAL;
18414        }
18415        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18416            scanFlags |= SCAN_DONT_KILL_APP;
18417        }
18418        if (instantApp) {
18419            scanFlags |= SCAN_AS_INSTANT_APP;
18420        }
18421        if (fullApp) {
18422            scanFlags |= SCAN_AS_FULL_APP;
18423        }
18424        if (virtualPreload) {
18425            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18426        }
18427
18428        // Result object to be returned
18429        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18430        res.installerPackageName = installerPackageName;
18431
18432        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18433
18434        // Sanity check
18435        if (instantApp && (forwardLocked || onExternal)) {
18436            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18437                    + " external=" + onExternal);
18438            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18439            return;
18440        }
18441
18442        // Retrieve PackageSettings and parse package
18443        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18444                | PackageParser.PARSE_ENFORCE_CODE
18445                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18446                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18447                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18448                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18449        PackageParser pp = new PackageParser();
18450        pp.setSeparateProcesses(mSeparateProcesses);
18451        pp.setDisplayMetrics(mMetrics);
18452        pp.setCallback(mPackageParserCallback);
18453
18454        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18455        final PackageParser.Package pkg;
18456        try {
18457            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18458        } catch (PackageParserException e) {
18459            res.setError("Failed parse during installPackageLI", e);
18460            return;
18461        } finally {
18462            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18463        }
18464
18465        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18466        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18467            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18468            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18469                    "Instant app package must target O");
18470            return;
18471        }
18472        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18473            Slog.w(TAG, "Instant app package " + pkg.packageName
18474                    + " does not target targetSandboxVersion 2");
18475            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18476                    "Instant app package must use targetSanboxVersion 2");
18477            return;
18478        }
18479
18480        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18481            // Static shared libraries have synthetic package names
18482            renameStaticSharedLibraryPackage(pkg);
18483
18484            // No static shared libs on external storage
18485            if (onExternal) {
18486                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18487                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18488                        "Packages declaring static-shared libs cannot be updated");
18489                return;
18490            }
18491        }
18492
18493        // If we are installing a clustered package add results for the children
18494        if (pkg.childPackages != null) {
18495            synchronized (mPackages) {
18496                final int childCount = pkg.childPackages.size();
18497                for (int i = 0; i < childCount; i++) {
18498                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18499                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18500                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18501                    childRes.pkg = childPkg;
18502                    childRes.name = childPkg.packageName;
18503                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18504                    if (childPs != null) {
18505                        childRes.origUsers = childPs.queryInstalledUsers(
18506                                sUserManager.getUserIds(), true);
18507                    }
18508                    if ((mPackages.containsKey(childPkg.packageName))) {
18509                        childRes.removedInfo = new PackageRemovedInfo(this);
18510                        childRes.removedInfo.removedPackage = childPkg.packageName;
18511                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18512                    }
18513                    if (res.addedChildPackages == null) {
18514                        res.addedChildPackages = new ArrayMap<>();
18515                    }
18516                    res.addedChildPackages.put(childPkg.packageName, childRes);
18517                }
18518            }
18519        }
18520
18521        // If package doesn't declare API override, mark that we have an install
18522        // time CPU ABI override.
18523        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18524            pkg.cpuAbiOverride = args.abiOverride;
18525        }
18526
18527        String pkgName = res.name = pkg.packageName;
18528        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18529            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18530                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18531                return;
18532            }
18533        }
18534
18535        try {
18536            // either use what we've been given or parse directly from the APK
18537            if (args.certificates != null) {
18538                try {
18539                    PackageParser.populateCertificates(pkg, args.certificates);
18540                } catch (PackageParserException e) {
18541                    // there was something wrong with the certificates we were given;
18542                    // try to pull them from the APK
18543                    PackageParser.collectCertificates(pkg, parseFlags);
18544                }
18545            } else {
18546                PackageParser.collectCertificates(pkg, parseFlags);
18547            }
18548        } catch (PackageParserException e) {
18549            res.setError("Failed collect during installPackageLI", e);
18550            return;
18551        }
18552
18553        // Get rid of all references to package scan path via parser.
18554        pp = null;
18555        String oldCodePath = null;
18556        boolean systemApp = false;
18557        synchronized (mPackages) {
18558            // Check if installing already existing package
18559            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18560                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18561                if (pkg.mOriginalPackages != null
18562                        && pkg.mOriginalPackages.contains(oldName)
18563                        && mPackages.containsKey(oldName)) {
18564                    // This package is derived from an original package,
18565                    // and this device has been updating from that original
18566                    // name.  We must continue using the original name, so
18567                    // rename the new package here.
18568                    pkg.setPackageName(oldName);
18569                    pkgName = pkg.packageName;
18570                    replace = true;
18571                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18572                            + oldName + " pkgName=" + pkgName);
18573                } else if (mPackages.containsKey(pkgName)) {
18574                    // This package, under its official name, already exists
18575                    // on the device; we should replace it.
18576                    replace = true;
18577                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18578                }
18579
18580                // Child packages are installed through the parent package
18581                if (pkg.parentPackage != null) {
18582                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18583                            "Package " + pkg.packageName + " is child of package "
18584                                    + pkg.parentPackage.parentPackage + ". Child packages "
18585                                    + "can be updated only through the parent package.");
18586                    return;
18587                }
18588
18589                if (replace) {
18590                    // Prevent apps opting out from runtime permissions
18591                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18592                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18593                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18594                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18595                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18596                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18597                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18598                                        + " doesn't support runtime permissions but the old"
18599                                        + " target SDK " + oldTargetSdk + " does.");
18600                        return;
18601                    }
18602                    // Prevent apps from downgrading their targetSandbox.
18603                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18604                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18605                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18606                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18607                                "Package " + pkg.packageName + " new target sandbox "
18608                                + newTargetSandbox + " is incompatible with the previous value of"
18609                                + oldTargetSandbox + ".");
18610                        return;
18611                    }
18612
18613                    // Prevent installing of child packages
18614                    if (oldPackage.parentPackage != null) {
18615                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18616                                "Package " + pkg.packageName + " is child of package "
18617                                        + oldPackage.parentPackage + ". Child packages "
18618                                        + "can be updated only through the parent package.");
18619                        return;
18620                    }
18621                }
18622            }
18623
18624            PackageSetting ps = mSettings.mPackages.get(pkgName);
18625            if (ps != null) {
18626                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18627
18628                // Static shared libs have same package with different versions where
18629                // we internally use a synthetic package name to allow multiple versions
18630                // of the same package, therefore we need to compare signatures against
18631                // the package setting for the latest library version.
18632                PackageSetting signatureCheckPs = ps;
18633                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18634                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18635                    if (libraryEntry != null) {
18636                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18637                    }
18638                }
18639
18640                // Quick sanity check that we're signed correctly if updating;
18641                // we'll check this again later when scanning, but we want to
18642                // bail early here before tripping over redefined permissions.
18643                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18644                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18645                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18646                                + pkg.packageName + " upgrade keys do not match the "
18647                                + "previously installed version");
18648                        return;
18649                    }
18650                } else {
18651                    try {
18652                        verifySignaturesLP(signatureCheckPs, pkg);
18653                    } catch (PackageManagerException e) {
18654                        res.setError(e.error, e.getMessage());
18655                        return;
18656                    }
18657                }
18658
18659                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18660                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18661                    systemApp = (ps.pkg.applicationInfo.flags &
18662                            ApplicationInfo.FLAG_SYSTEM) != 0;
18663                }
18664                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18665            }
18666
18667            int N = pkg.permissions.size();
18668            for (int i = N-1; i >= 0; i--) {
18669                PackageParser.Permission perm = pkg.permissions.get(i);
18670                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18671
18672                // Don't allow anyone but the system to define ephemeral permissions.
18673                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18674                        && !systemApp) {
18675                    Slog.w(TAG, "Non-System package " + pkg.packageName
18676                            + " attempting to delcare ephemeral permission "
18677                            + perm.info.name + "; Removing ephemeral.");
18678                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18679                }
18680
18681                // Check whether the newly-scanned package wants to define an already-defined perm
18682                if (bp != null) {
18683                    // If the defining package is signed with our cert, it's okay.  This
18684                    // also includes the "updating the same package" case, of course.
18685                    // "updating same package" could also involve key-rotation.
18686                    final boolean sigsOk;
18687                    if (bp.sourcePackage.equals(pkg.packageName)
18688                            && (bp.packageSetting instanceof PackageSetting)
18689                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18690                                    scanFlags))) {
18691                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18692                    } else {
18693                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18694                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18695                    }
18696                    if (!sigsOk) {
18697                        // If the owning package is the system itself, we log but allow
18698                        // install to proceed; we fail the install on all other permission
18699                        // redefinitions.
18700                        if (!bp.sourcePackage.equals("android")) {
18701                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18702                                    + pkg.packageName + " attempting to redeclare permission "
18703                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18704                            res.origPermission = perm.info.name;
18705                            res.origPackage = bp.sourcePackage;
18706                            return;
18707                        } else {
18708                            Slog.w(TAG, "Package " + pkg.packageName
18709                                    + " attempting to redeclare system permission "
18710                                    + perm.info.name + "; ignoring new declaration");
18711                            pkg.permissions.remove(i);
18712                        }
18713                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18714                        // Prevent apps to change protection level to dangerous from any other
18715                        // type as this would allow a privilege escalation where an app adds a
18716                        // normal/signature permission in other app's group and later redefines
18717                        // it as dangerous leading to the group auto-grant.
18718                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18719                                == PermissionInfo.PROTECTION_DANGEROUS) {
18720                            if (bp != null && !bp.isRuntime()) {
18721                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18722                                        + "non-runtime permission " + perm.info.name
18723                                        + " to runtime; keeping old protection level");
18724                                perm.info.protectionLevel = bp.protectionLevel;
18725                            }
18726                        }
18727                    }
18728                }
18729            }
18730        }
18731
18732        if (systemApp) {
18733            if (onExternal) {
18734                // Abort update; system app can't be replaced with app on sdcard
18735                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18736                        "Cannot install updates to system apps on sdcard");
18737                return;
18738            } else if (instantApp) {
18739                // Abort update; system app can't be replaced with an instant app
18740                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18741                        "Cannot update a system app with an instant app");
18742                return;
18743            }
18744        }
18745
18746        if (args.move != null) {
18747            // We did an in-place move, so dex is ready to roll
18748            scanFlags |= SCAN_NO_DEX;
18749            scanFlags |= SCAN_MOVE;
18750
18751            synchronized (mPackages) {
18752                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18753                if (ps == null) {
18754                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18755                            "Missing settings for moved package " + pkgName);
18756                }
18757
18758                // We moved the entire application as-is, so bring over the
18759                // previously derived ABI information.
18760                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18761                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18762            }
18763
18764        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18765            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18766            scanFlags |= SCAN_NO_DEX;
18767
18768            try {
18769                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18770                    args.abiOverride : pkg.cpuAbiOverride);
18771                final boolean extractNativeLibs = !pkg.isLibrary();
18772                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18773                        extractNativeLibs, mAppLib32InstallDir);
18774            } catch (PackageManagerException pme) {
18775                Slog.e(TAG, "Error deriving application ABI", pme);
18776                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18777                return;
18778            }
18779
18780            // Shared libraries for the package need to be updated.
18781            synchronized (mPackages) {
18782                try {
18783                    updateSharedLibrariesLPr(pkg, null);
18784                } catch (PackageManagerException e) {
18785                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18786                }
18787            }
18788        }
18789
18790        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18791            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18792            return;
18793        }
18794
18795        // Verify if we need to dexopt the app.
18796        //
18797        // NOTE: it is *important* to call dexopt after doRename which will sync the
18798        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18799        //
18800        // We only need to dexopt if the package meets ALL of the following conditions:
18801        //   1) it is not forward locked.
18802        //   2) it is not on on an external ASEC container.
18803        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18804        //
18805        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18806        // complete, so we skip this step during installation. Instead, we'll take extra time
18807        // the first time the instant app starts. It's preferred to do it this way to provide
18808        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18809        // middle of running an instant app. The default behaviour can be overridden
18810        // via gservices.
18811        final boolean performDexopt = !forwardLocked
18812            && !pkg.applicationInfo.isExternalAsec()
18813            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18814                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18815
18816        if (performDexopt) {
18817            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18818            // Do not run PackageDexOptimizer through the local performDexOpt
18819            // method because `pkg` may not be in `mPackages` yet.
18820            //
18821            // Also, don't fail application installs if the dexopt step fails.
18822            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18823                REASON_INSTALL,
18824                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18825            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18826                null /* instructionSets */,
18827                getOrCreateCompilerPackageStats(pkg),
18828                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18829                dexoptOptions);
18830            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18831        }
18832
18833        // Notify BackgroundDexOptService that the package has been changed.
18834        // If this is an update of a package which used to fail to compile,
18835        // BackgroundDexOptService will remove it from its blacklist.
18836        // TODO: Layering violation
18837        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18838
18839        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18840
18841        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18842                "installPackageLI")) {
18843            if (replace) {
18844                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18845                    // Static libs have a synthetic package name containing the version
18846                    // and cannot be updated as an update would get a new package name,
18847                    // unless this is the exact same version code which is useful for
18848                    // development.
18849                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18850                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18851                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18852                                + "static-shared libs cannot be updated");
18853                        return;
18854                    }
18855                }
18856                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18857                        installerPackageName, res, args.installReason);
18858            } else {
18859                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18860                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18861            }
18862        }
18863
18864        synchronized (mPackages) {
18865            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18866            if (ps != null) {
18867                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18868                ps.setUpdateAvailable(false /*updateAvailable*/);
18869            }
18870
18871            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18872            for (int i = 0; i < childCount; i++) {
18873                PackageParser.Package childPkg = pkg.childPackages.get(i);
18874                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18875                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18876                if (childPs != null) {
18877                    childRes.newUsers = childPs.queryInstalledUsers(
18878                            sUserManager.getUserIds(), true);
18879                }
18880            }
18881
18882            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18883                updateSequenceNumberLP(ps, res.newUsers);
18884                updateInstantAppInstallerLocked(pkgName);
18885            }
18886        }
18887    }
18888
18889    private void startIntentFilterVerifications(int userId, boolean replacing,
18890            PackageParser.Package pkg) {
18891        if (mIntentFilterVerifierComponent == null) {
18892            Slog.w(TAG, "No IntentFilter verification will not be done as "
18893                    + "there is no IntentFilterVerifier available!");
18894            return;
18895        }
18896
18897        final int verifierUid = getPackageUid(
18898                mIntentFilterVerifierComponent.getPackageName(),
18899                MATCH_DEBUG_TRIAGED_MISSING,
18900                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18901
18902        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18903        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18904        mHandler.sendMessage(msg);
18905
18906        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18907        for (int i = 0; i < childCount; i++) {
18908            PackageParser.Package childPkg = pkg.childPackages.get(i);
18909            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18910            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18911            mHandler.sendMessage(msg);
18912        }
18913    }
18914
18915    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18916            PackageParser.Package pkg) {
18917        int size = pkg.activities.size();
18918        if (size == 0) {
18919            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18920                    "No activity, so no need to verify any IntentFilter!");
18921            return;
18922        }
18923
18924        final boolean hasDomainURLs = hasDomainURLs(pkg);
18925        if (!hasDomainURLs) {
18926            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18927                    "No domain URLs, so no need to verify any IntentFilter!");
18928            return;
18929        }
18930
18931        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18932                + " if any IntentFilter from the " + size
18933                + " Activities needs verification ...");
18934
18935        int count = 0;
18936        final String packageName = pkg.packageName;
18937
18938        synchronized (mPackages) {
18939            // If this is a new install and we see that we've already run verification for this
18940            // package, we have nothing to do: it means the state was restored from backup.
18941            if (!replacing) {
18942                IntentFilterVerificationInfo ivi =
18943                        mSettings.getIntentFilterVerificationLPr(packageName);
18944                if (ivi != null) {
18945                    if (DEBUG_DOMAIN_VERIFICATION) {
18946                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18947                                + ivi.getStatusString());
18948                    }
18949                    return;
18950                }
18951            }
18952
18953            // If any filters need to be verified, then all need to be.
18954            boolean needToVerify = false;
18955            for (PackageParser.Activity a : pkg.activities) {
18956                for (ActivityIntentInfo filter : a.intents) {
18957                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18958                        if (DEBUG_DOMAIN_VERIFICATION) {
18959                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18960                        }
18961                        needToVerify = true;
18962                        break;
18963                    }
18964                }
18965            }
18966
18967            if (needToVerify) {
18968                final int verificationId = mIntentFilterVerificationToken++;
18969                for (PackageParser.Activity a : pkg.activities) {
18970                    for (ActivityIntentInfo filter : a.intents) {
18971                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18972                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18973                                    "Verification needed for IntentFilter:" + filter.toString());
18974                            mIntentFilterVerifier.addOneIntentFilterVerification(
18975                                    verifierUid, userId, verificationId, filter, packageName);
18976                            count++;
18977                        }
18978                    }
18979                }
18980            }
18981        }
18982
18983        if (count > 0) {
18984            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18985                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18986                    +  " for userId:" + userId);
18987            mIntentFilterVerifier.startVerifications(userId);
18988        } else {
18989            if (DEBUG_DOMAIN_VERIFICATION) {
18990                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18991            }
18992        }
18993    }
18994
18995    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18996        final ComponentName cn  = filter.activity.getComponentName();
18997        final String packageName = cn.getPackageName();
18998
18999        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
19000                packageName);
19001        if (ivi == null) {
19002            return true;
19003        }
19004        int status = ivi.getStatus();
19005        switch (status) {
19006            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
19007            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
19008                return true;
19009
19010            default:
19011                // Nothing to do
19012                return false;
19013        }
19014    }
19015
19016    private static boolean isMultiArch(ApplicationInfo info) {
19017        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
19018    }
19019
19020    private static boolean isExternal(PackageParser.Package pkg) {
19021        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19022    }
19023
19024    private static boolean isExternal(PackageSetting ps) {
19025        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19026    }
19027
19028    private static boolean isSystemApp(PackageParser.Package pkg) {
19029        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
19030    }
19031
19032    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
19033        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
19034    }
19035
19036    private static boolean isOemApp(PackageParser.Package pkg) {
19037        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
19038    }
19039
19040    private static boolean hasDomainURLs(PackageParser.Package pkg) {
19041        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
19042    }
19043
19044    private static boolean isSystemApp(PackageSetting ps) {
19045        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
19046    }
19047
19048    private static boolean isUpdatedSystemApp(PackageSetting ps) {
19049        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
19050    }
19051
19052    private int packageFlagsToInstallFlags(PackageSetting ps) {
19053        int installFlags = 0;
19054        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19055            // This existing package was an external ASEC install when we have
19056            // the external flag without a UUID
19057            installFlags |= PackageManager.INSTALL_EXTERNAL;
19058        }
19059        if (ps.isForwardLocked()) {
19060            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19061        }
19062        return installFlags;
19063    }
19064
19065    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19066        if (isExternal(pkg)) {
19067            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19068                return StorageManager.UUID_PRIMARY_PHYSICAL;
19069            } else {
19070                return pkg.volumeUuid;
19071            }
19072        } else {
19073            return StorageManager.UUID_PRIVATE_INTERNAL;
19074        }
19075    }
19076
19077    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19078        if (isExternal(pkg)) {
19079            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19080                return mSettings.getExternalVersion();
19081            } else {
19082                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19083            }
19084        } else {
19085            return mSettings.getInternalVersion();
19086        }
19087    }
19088
19089    private void deleteTempPackageFiles() {
19090        final FilenameFilter filter = new FilenameFilter() {
19091            public boolean accept(File dir, String name) {
19092                return name.startsWith("vmdl") && name.endsWith(".tmp");
19093            }
19094        };
19095        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19096            file.delete();
19097        }
19098    }
19099
19100    @Override
19101    public void deletePackageAsUser(String packageName, int versionCode,
19102            IPackageDeleteObserver observer, int userId, int flags) {
19103        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19104                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19105    }
19106
19107    @Override
19108    public void deletePackageVersioned(VersionedPackage versionedPackage,
19109            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19110        final int callingUid = Binder.getCallingUid();
19111        mContext.enforceCallingOrSelfPermission(
19112                android.Manifest.permission.DELETE_PACKAGES, null);
19113        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19114        Preconditions.checkNotNull(versionedPackage);
19115        Preconditions.checkNotNull(observer);
19116        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19117                PackageManager.VERSION_CODE_HIGHEST,
19118                Integer.MAX_VALUE, "versionCode must be >= -1");
19119
19120        final String packageName = versionedPackage.getPackageName();
19121        final int versionCode = versionedPackage.getVersionCode();
19122        final String internalPackageName;
19123        synchronized (mPackages) {
19124            // Normalize package name to handle renamed packages and static libs
19125            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19126                    versionedPackage.getVersionCode());
19127        }
19128
19129        final int uid = Binder.getCallingUid();
19130        if (!isOrphaned(internalPackageName)
19131                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19132            try {
19133                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19134                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19135                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19136                observer.onUserActionRequired(intent);
19137            } catch (RemoteException re) {
19138            }
19139            return;
19140        }
19141        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19142        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19143        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19144            mContext.enforceCallingOrSelfPermission(
19145                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19146                    "deletePackage for user " + userId);
19147        }
19148
19149        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19150            try {
19151                observer.onPackageDeleted(packageName,
19152                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19153            } catch (RemoteException re) {
19154            }
19155            return;
19156        }
19157
19158        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19159            try {
19160                observer.onPackageDeleted(packageName,
19161                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19162            } catch (RemoteException re) {
19163            }
19164            return;
19165        }
19166
19167        if (DEBUG_REMOVE) {
19168            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19169                    + " deleteAllUsers: " + deleteAllUsers + " version="
19170                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19171                    ? "VERSION_CODE_HIGHEST" : versionCode));
19172        }
19173        // Queue up an async operation since the package deletion may take a little while.
19174        mHandler.post(new Runnable() {
19175            public void run() {
19176                mHandler.removeCallbacks(this);
19177                int returnCode;
19178                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19179                boolean doDeletePackage = true;
19180                if (ps != null) {
19181                    final boolean targetIsInstantApp =
19182                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19183                    doDeletePackage = !targetIsInstantApp
19184                            || canViewInstantApps;
19185                }
19186                if (doDeletePackage) {
19187                    if (!deleteAllUsers) {
19188                        returnCode = deletePackageX(internalPackageName, versionCode,
19189                                userId, deleteFlags);
19190                    } else {
19191                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19192                                internalPackageName, users);
19193                        // If nobody is blocking uninstall, proceed with delete for all users
19194                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19195                            returnCode = deletePackageX(internalPackageName, versionCode,
19196                                    userId, deleteFlags);
19197                        } else {
19198                            // Otherwise uninstall individually for users with blockUninstalls=false
19199                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19200                            for (int userId : users) {
19201                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19202                                    returnCode = deletePackageX(internalPackageName, versionCode,
19203                                            userId, userFlags);
19204                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19205                                        Slog.w(TAG, "Package delete failed for user " + userId
19206                                                + ", returnCode " + returnCode);
19207                                    }
19208                                }
19209                            }
19210                            // The app has only been marked uninstalled for certain users.
19211                            // We still need to report that delete was blocked
19212                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19213                        }
19214                    }
19215                } else {
19216                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19217                }
19218                try {
19219                    observer.onPackageDeleted(packageName, returnCode, null);
19220                } catch (RemoteException e) {
19221                    Log.i(TAG, "Observer no longer exists.");
19222                } //end catch
19223            } //end run
19224        });
19225    }
19226
19227    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19228        if (pkg.staticSharedLibName != null) {
19229            return pkg.manifestPackageName;
19230        }
19231        return pkg.packageName;
19232    }
19233
19234    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19235        // Handle renamed packages
19236        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19237        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19238
19239        // Is this a static library?
19240        SparseArray<SharedLibraryEntry> versionedLib =
19241                mStaticLibsByDeclaringPackage.get(packageName);
19242        if (versionedLib == null || versionedLib.size() <= 0) {
19243            return packageName;
19244        }
19245
19246        // Figure out which lib versions the caller can see
19247        SparseIntArray versionsCallerCanSee = null;
19248        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19249        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19250                && callingAppId != Process.ROOT_UID) {
19251            versionsCallerCanSee = new SparseIntArray();
19252            String libName = versionedLib.valueAt(0).info.getName();
19253            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19254            if (uidPackages != null) {
19255                for (String uidPackage : uidPackages) {
19256                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19257                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19258                    if (libIdx >= 0) {
19259                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19260                        versionsCallerCanSee.append(libVersion, libVersion);
19261                    }
19262                }
19263            }
19264        }
19265
19266        // Caller can see nothing - done
19267        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19268            return packageName;
19269        }
19270
19271        // Find the version the caller can see and the app version code
19272        SharedLibraryEntry highestVersion = null;
19273        final int versionCount = versionedLib.size();
19274        for (int i = 0; i < versionCount; i++) {
19275            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19276            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19277                    libEntry.info.getVersion()) < 0) {
19278                continue;
19279            }
19280            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19281            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19282                if (libVersionCode == versionCode) {
19283                    return libEntry.apk;
19284                }
19285            } else if (highestVersion == null) {
19286                highestVersion = libEntry;
19287            } else if (libVersionCode  > highestVersion.info
19288                    .getDeclaringPackage().getVersionCode()) {
19289                highestVersion = libEntry;
19290            }
19291        }
19292
19293        if (highestVersion != null) {
19294            return highestVersion.apk;
19295        }
19296
19297        return packageName;
19298    }
19299
19300    boolean isCallerVerifier(int callingUid) {
19301        final int callingUserId = UserHandle.getUserId(callingUid);
19302        return mRequiredVerifierPackage != null &&
19303                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19304    }
19305
19306    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19307        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19308              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19309            return true;
19310        }
19311        final int callingUserId = UserHandle.getUserId(callingUid);
19312        // If the caller installed the pkgName, then allow it to silently uninstall.
19313        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19314            return true;
19315        }
19316
19317        // Allow package verifier to silently uninstall.
19318        if (mRequiredVerifierPackage != null &&
19319                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19320            return true;
19321        }
19322
19323        // Allow package uninstaller to silently uninstall.
19324        if (mRequiredUninstallerPackage != null &&
19325                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19326            return true;
19327        }
19328
19329        // Allow storage manager to silently uninstall.
19330        if (mStorageManagerPackage != null &&
19331                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19332            return true;
19333        }
19334
19335        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19336        // uninstall for device owner provisioning.
19337        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19338                == PERMISSION_GRANTED) {
19339            return true;
19340        }
19341
19342        return false;
19343    }
19344
19345    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19346        int[] result = EMPTY_INT_ARRAY;
19347        for (int userId : userIds) {
19348            if (getBlockUninstallForUser(packageName, userId)) {
19349                result = ArrayUtils.appendInt(result, userId);
19350            }
19351        }
19352        return result;
19353    }
19354
19355    @Override
19356    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19357        final int callingUid = Binder.getCallingUid();
19358        if (getInstantAppPackageName(callingUid) != null
19359                && !isCallerSameApp(packageName, callingUid)) {
19360            return false;
19361        }
19362        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19363    }
19364
19365    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19366        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19367                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19368        try {
19369            if (dpm != null) {
19370                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19371                        /* callingUserOnly =*/ false);
19372                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19373                        : deviceOwnerComponentName.getPackageName();
19374                // Does the package contains the device owner?
19375                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19376                // this check is probably not needed, since DO should be registered as a device
19377                // admin on some user too. (Original bug for this: b/17657954)
19378                if (packageName.equals(deviceOwnerPackageName)) {
19379                    return true;
19380                }
19381                // Does it contain a device admin for any user?
19382                int[] users;
19383                if (userId == UserHandle.USER_ALL) {
19384                    users = sUserManager.getUserIds();
19385                } else {
19386                    users = new int[]{userId};
19387                }
19388                for (int i = 0; i < users.length; ++i) {
19389                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19390                        return true;
19391                    }
19392                }
19393            }
19394        } catch (RemoteException e) {
19395        }
19396        return false;
19397    }
19398
19399    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19400        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19401    }
19402
19403    /**
19404     *  This method is an internal method that could be get invoked either
19405     *  to delete an installed package or to clean up a failed installation.
19406     *  After deleting an installed package, a broadcast is sent to notify any
19407     *  listeners that the package has been removed. For cleaning up a failed
19408     *  installation, the broadcast is not necessary since the package's
19409     *  installation wouldn't have sent the initial broadcast either
19410     *  The key steps in deleting a package are
19411     *  deleting the package information in internal structures like mPackages,
19412     *  deleting the packages base directories through installd
19413     *  updating mSettings to reflect current status
19414     *  persisting settings for later use
19415     *  sending a broadcast if necessary
19416     */
19417    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19418        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19419        final boolean res;
19420
19421        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19422                ? UserHandle.USER_ALL : userId;
19423
19424        if (isPackageDeviceAdmin(packageName, removeUser)) {
19425            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19426            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19427        }
19428
19429        PackageSetting uninstalledPs = null;
19430        PackageParser.Package pkg = null;
19431
19432        // for the uninstall-updates case and restricted profiles, remember the per-
19433        // user handle installed state
19434        int[] allUsers;
19435        synchronized (mPackages) {
19436            uninstalledPs = mSettings.mPackages.get(packageName);
19437            if (uninstalledPs == null) {
19438                Slog.w(TAG, "Not removing non-existent package " + packageName);
19439                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19440            }
19441
19442            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19443                    && uninstalledPs.versionCode != versionCode) {
19444                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19445                        + uninstalledPs.versionCode + " != " + versionCode);
19446                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19447            }
19448
19449            // Static shared libs can be declared by any package, so let us not
19450            // allow removing a package if it provides a lib others depend on.
19451            pkg = mPackages.get(packageName);
19452
19453            allUsers = sUserManager.getUserIds();
19454
19455            if (pkg != null && pkg.staticSharedLibName != null) {
19456                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19457                        pkg.staticSharedLibVersion);
19458                if (libEntry != null) {
19459                    for (int currUserId : allUsers) {
19460                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19461                            continue;
19462                        }
19463                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19464                                libEntry.info, 0, currUserId);
19465                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19466                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19467                                    + " hosting lib " + libEntry.info.getName() + " version "
19468                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19469                                    + " for user " + currUserId);
19470                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19471                        }
19472                    }
19473                }
19474            }
19475
19476            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19477        }
19478
19479        final int freezeUser;
19480        if (isUpdatedSystemApp(uninstalledPs)
19481                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19482            // We're downgrading a system app, which will apply to all users, so
19483            // freeze them all during the downgrade
19484            freezeUser = UserHandle.USER_ALL;
19485        } else {
19486            freezeUser = removeUser;
19487        }
19488
19489        synchronized (mInstallLock) {
19490            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19491            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19492                    deleteFlags, "deletePackageX")) {
19493                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19494                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19495            }
19496            synchronized (mPackages) {
19497                if (res) {
19498                    if (pkg != null) {
19499                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19500                    }
19501                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19502                    updateInstantAppInstallerLocked(packageName);
19503                }
19504            }
19505        }
19506
19507        if (res) {
19508            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19509            info.sendPackageRemovedBroadcasts(killApp);
19510            info.sendSystemPackageUpdatedBroadcasts();
19511            info.sendSystemPackageAppearedBroadcasts();
19512        }
19513        // Force a gc here.
19514        Runtime.getRuntime().gc();
19515        // Delete the resources here after sending the broadcast to let
19516        // other processes clean up before deleting resources.
19517        if (info.args != null) {
19518            synchronized (mInstallLock) {
19519                info.args.doPostDeleteLI(true);
19520            }
19521        }
19522
19523        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19524    }
19525
19526    static class PackageRemovedInfo {
19527        final PackageSender packageSender;
19528        String removedPackage;
19529        String installerPackageName;
19530        int uid = -1;
19531        int removedAppId = -1;
19532        int[] origUsers;
19533        int[] removedUsers = null;
19534        int[] broadcastUsers = null;
19535        SparseArray<Integer> installReasons;
19536        boolean isRemovedPackageSystemUpdate = false;
19537        boolean isUpdate;
19538        boolean dataRemoved;
19539        boolean removedForAllUsers;
19540        boolean isStaticSharedLib;
19541        // Clean up resources deleted packages.
19542        InstallArgs args = null;
19543        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19544        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19545
19546        PackageRemovedInfo(PackageSender packageSender) {
19547            this.packageSender = packageSender;
19548        }
19549
19550        void sendPackageRemovedBroadcasts(boolean killApp) {
19551            sendPackageRemovedBroadcastInternal(killApp);
19552            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19553            for (int i = 0; i < childCount; i++) {
19554                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19555                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19556            }
19557        }
19558
19559        void sendSystemPackageUpdatedBroadcasts() {
19560            if (isRemovedPackageSystemUpdate) {
19561                sendSystemPackageUpdatedBroadcastsInternal();
19562                final int childCount = (removedChildPackages != null)
19563                        ? removedChildPackages.size() : 0;
19564                for (int i = 0; i < childCount; i++) {
19565                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19566                    if (childInfo.isRemovedPackageSystemUpdate) {
19567                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19568                    }
19569                }
19570            }
19571        }
19572
19573        void sendSystemPackageAppearedBroadcasts() {
19574            final int packageCount = (appearedChildPackages != null)
19575                    ? appearedChildPackages.size() : 0;
19576            for (int i = 0; i < packageCount; i++) {
19577                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19578                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19579                    true /*sendBootCompleted*/, false /*startReceiver*/,
19580                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19581            }
19582        }
19583
19584        private void sendSystemPackageUpdatedBroadcastsInternal() {
19585            Bundle extras = new Bundle(2);
19586            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19587            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19588            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19589                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19590            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19591                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19592            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19593                null, null, 0, removedPackage, null, null);
19594            if (installerPackageName != null) {
19595                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19596                        removedPackage, extras, 0 /*flags*/,
19597                        installerPackageName, null, null);
19598                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19599                        removedPackage, extras, 0 /*flags*/,
19600                        installerPackageName, null, null);
19601            }
19602        }
19603
19604        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19605            // Don't send static shared library removal broadcasts as these
19606            // libs are visible only the the apps that depend on them an one
19607            // cannot remove the library if it has a dependency.
19608            if (isStaticSharedLib) {
19609                return;
19610            }
19611            Bundle extras = new Bundle(2);
19612            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19613            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19614            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19615            if (isUpdate || isRemovedPackageSystemUpdate) {
19616                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19617            }
19618            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19619            if (removedPackage != null) {
19620                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19621                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19622                if (installerPackageName != null) {
19623                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19624                            removedPackage, extras, 0 /*flags*/,
19625                            installerPackageName, null, broadcastUsers);
19626                }
19627                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19628                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19629                        removedPackage, extras,
19630                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19631                        null, null, broadcastUsers);
19632                }
19633            }
19634            if (removedAppId >= 0) {
19635                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19636                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19637                    null, null, broadcastUsers);
19638            }
19639        }
19640
19641        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19642            removedUsers = userIds;
19643            if (removedUsers == null) {
19644                broadcastUsers = null;
19645                return;
19646            }
19647
19648            broadcastUsers = EMPTY_INT_ARRAY;
19649            for (int i = userIds.length - 1; i >= 0; --i) {
19650                final int userId = userIds[i];
19651                if (deletedPackageSetting.getInstantApp(userId)) {
19652                    continue;
19653                }
19654                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19655            }
19656        }
19657    }
19658
19659    /*
19660     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19661     * flag is not set, the data directory is removed as well.
19662     * make sure this flag is set for partially installed apps. If not its meaningless to
19663     * delete a partially installed application.
19664     */
19665    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19666            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19667        String packageName = ps.name;
19668        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19669        // Retrieve object to delete permissions for shared user later on
19670        final PackageParser.Package deletedPkg;
19671        final PackageSetting deletedPs;
19672        // reader
19673        synchronized (mPackages) {
19674            deletedPkg = mPackages.get(packageName);
19675            deletedPs = mSettings.mPackages.get(packageName);
19676            if (outInfo != null) {
19677                outInfo.removedPackage = packageName;
19678                outInfo.installerPackageName = ps.installerPackageName;
19679                outInfo.isStaticSharedLib = deletedPkg != null
19680                        && deletedPkg.staticSharedLibName != null;
19681                outInfo.populateUsers(deletedPs == null ? null
19682                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19683            }
19684        }
19685
19686        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19687
19688        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19689            final PackageParser.Package resolvedPkg;
19690            if (deletedPkg != null) {
19691                resolvedPkg = deletedPkg;
19692            } else {
19693                // We don't have a parsed package when it lives on an ejected
19694                // adopted storage device, so fake something together
19695                resolvedPkg = new PackageParser.Package(ps.name);
19696                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19697            }
19698            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19699                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19700            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19701            if (outInfo != null) {
19702                outInfo.dataRemoved = true;
19703            }
19704            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19705        }
19706
19707        int removedAppId = -1;
19708
19709        // writer
19710        synchronized (mPackages) {
19711            boolean installedStateChanged = false;
19712            if (deletedPs != null) {
19713                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19714                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19715                    clearDefaultBrowserIfNeeded(packageName);
19716                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19717                    removedAppId = mSettings.removePackageLPw(packageName);
19718                    if (outInfo != null) {
19719                        outInfo.removedAppId = removedAppId;
19720                    }
19721                    updatePermissionsLPw(deletedPs.name, null, 0);
19722                    if (deletedPs.sharedUser != null) {
19723                        // Remove permissions associated with package. Since runtime
19724                        // permissions are per user we have to kill the removed package
19725                        // or packages running under the shared user of the removed
19726                        // package if revoking the permissions requested only by the removed
19727                        // package is successful and this causes a change in gids.
19728                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19729                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19730                                    userId);
19731                            if (userIdToKill == UserHandle.USER_ALL
19732                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19733                                // If gids changed for this user, kill all affected packages.
19734                                mHandler.post(new Runnable() {
19735                                    @Override
19736                                    public void run() {
19737                                        // This has to happen with no lock held.
19738                                        killApplication(deletedPs.name, deletedPs.appId,
19739                                                KILL_APP_REASON_GIDS_CHANGED);
19740                                    }
19741                                });
19742                                break;
19743                            }
19744                        }
19745                    }
19746                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19747                }
19748                // make sure to preserve per-user disabled state if this removal was just
19749                // a downgrade of a system app to the factory package
19750                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19751                    if (DEBUG_REMOVE) {
19752                        Slog.d(TAG, "Propagating install state across downgrade");
19753                    }
19754                    for (int userId : allUserHandles) {
19755                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19756                        if (DEBUG_REMOVE) {
19757                            Slog.d(TAG, "    user " + userId + " => " + installed);
19758                        }
19759                        if (installed != ps.getInstalled(userId)) {
19760                            installedStateChanged = true;
19761                        }
19762                        ps.setInstalled(installed, userId);
19763                    }
19764                }
19765            }
19766            // can downgrade to reader
19767            if (writeSettings) {
19768                // Save settings now
19769                mSettings.writeLPr();
19770            }
19771            if (installedStateChanged) {
19772                mSettings.writeKernelMappingLPr(ps);
19773            }
19774        }
19775        if (removedAppId != -1) {
19776            // A user ID was deleted here. Go through all users and remove it
19777            // from KeyStore.
19778            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19779        }
19780    }
19781
19782    static boolean locationIsPrivileged(File path) {
19783        try {
19784            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19785                    .getCanonicalPath();
19786            return path.getCanonicalPath().startsWith(privilegedAppDir);
19787        } catch (IOException e) {
19788            Slog.e(TAG, "Unable to access code path " + path);
19789        }
19790        return false;
19791    }
19792
19793    static boolean locationIsOem(File path) {
19794        try {
19795            return path.getCanonicalPath().startsWith(
19796                    Environment.getOemDirectory().getCanonicalPath());
19797        } catch (IOException e) {
19798            Slog.e(TAG, "Unable to access code path " + path);
19799        }
19800        return false;
19801    }
19802
19803    /*
19804     * Tries to delete system package.
19805     */
19806    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19807            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19808            boolean writeSettings) {
19809        if (deletedPs.parentPackageName != null) {
19810            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19811            return false;
19812        }
19813
19814        final boolean applyUserRestrictions
19815                = (allUserHandles != null) && (outInfo.origUsers != null);
19816        final PackageSetting disabledPs;
19817        // Confirm if the system package has been updated
19818        // An updated system app can be deleted. This will also have to restore
19819        // the system pkg from system partition
19820        // reader
19821        synchronized (mPackages) {
19822            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19823        }
19824
19825        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19826                + " disabledPs=" + disabledPs);
19827
19828        if (disabledPs == null) {
19829            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19830            return false;
19831        } else if (DEBUG_REMOVE) {
19832            Slog.d(TAG, "Deleting system pkg from data partition");
19833        }
19834
19835        if (DEBUG_REMOVE) {
19836            if (applyUserRestrictions) {
19837                Slog.d(TAG, "Remembering install states:");
19838                for (int userId : allUserHandles) {
19839                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19840                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19841                }
19842            }
19843        }
19844
19845        // Delete the updated package
19846        outInfo.isRemovedPackageSystemUpdate = true;
19847        if (outInfo.removedChildPackages != null) {
19848            final int childCount = (deletedPs.childPackageNames != null)
19849                    ? deletedPs.childPackageNames.size() : 0;
19850            for (int i = 0; i < childCount; i++) {
19851                String childPackageName = deletedPs.childPackageNames.get(i);
19852                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19853                        .contains(childPackageName)) {
19854                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19855                            childPackageName);
19856                    if (childInfo != null) {
19857                        childInfo.isRemovedPackageSystemUpdate = true;
19858                    }
19859                }
19860            }
19861        }
19862
19863        if (disabledPs.versionCode < deletedPs.versionCode) {
19864            // Delete data for downgrades
19865            flags &= ~PackageManager.DELETE_KEEP_DATA;
19866        } else {
19867            // Preserve data by setting flag
19868            flags |= PackageManager.DELETE_KEEP_DATA;
19869        }
19870
19871        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19872                outInfo, writeSettings, disabledPs.pkg);
19873        if (!ret) {
19874            return false;
19875        }
19876
19877        // writer
19878        synchronized (mPackages) {
19879            // NOTE: The system package always needs to be enabled; even if it's for
19880            // a compressed stub. If we don't, installing the system package fails
19881            // during scan [scanning checks the disabled packages]. We will reverse
19882            // this later, after we've "installed" the stub.
19883            // Reinstate the old system package
19884            enableSystemPackageLPw(disabledPs.pkg);
19885            // Remove any native libraries from the upgraded package.
19886            removeNativeBinariesLI(deletedPs);
19887        }
19888
19889        // Install the system package
19890        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19891        try {
19892            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19893                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19894        } catch (PackageManagerException e) {
19895            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19896                    + e.getMessage());
19897            return false;
19898        } finally {
19899            if (disabledPs.pkg.isStub) {
19900                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19901            }
19902        }
19903        return true;
19904    }
19905
19906    /**
19907     * Installs a package that's already on the system partition.
19908     */
19909    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19910            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19911            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19912                    throws PackageManagerException {
19913        int parseFlags = mDefParseFlags
19914                | PackageParser.PARSE_MUST_BE_APK
19915                | PackageParser.PARSE_IS_SYSTEM
19916                | PackageParser.PARSE_IS_SYSTEM_DIR;
19917        if (isPrivileged || locationIsPrivileged(codePath)) {
19918            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19919        }
19920        if (locationIsOem(codePath)) {
19921            parseFlags |= PackageParser.PARSE_IS_OEM;
19922        }
19923
19924        final PackageParser.Package newPkg =
19925                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19926
19927        try {
19928            // update shared libraries for the newly re-installed system package
19929            updateSharedLibrariesLPr(newPkg, null);
19930        } catch (PackageManagerException e) {
19931            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19932        }
19933
19934        prepareAppDataAfterInstallLIF(newPkg);
19935
19936        // writer
19937        synchronized (mPackages) {
19938            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19939
19940            // Propagate the permissions state as we do not want to drop on the floor
19941            // runtime permissions. The update permissions method below will take
19942            // care of removing obsolete permissions and grant install permissions.
19943            if (origPermissionState != null) {
19944                ps.getPermissionsState().copyFrom(origPermissionState);
19945            }
19946            updatePermissionsLPw(newPkg.packageName, newPkg,
19947                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19948
19949            final boolean applyUserRestrictions
19950                    = (allUserHandles != null) && (origUserHandles != null);
19951            if (applyUserRestrictions) {
19952                boolean installedStateChanged = false;
19953                if (DEBUG_REMOVE) {
19954                    Slog.d(TAG, "Propagating install state across reinstall");
19955                }
19956                for (int userId : allUserHandles) {
19957                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19958                    if (DEBUG_REMOVE) {
19959                        Slog.d(TAG, "    user " + userId + " => " + installed);
19960                    }
19961                    if (installed != ps.getInstalled(userId)) {
19962                        installedStateChanged = true;
19963                    }
19964                    ps.setInstalled(installed, userId);
19965
19966                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19967                }
19968                // Regardless of writeSettings we need to ensure that this restriction
19969                // state propagation is persisted
19970                mSettings.writeAllUsersPackageRestrictionsLPr();
19971                if (installedStateChanged) {
19972                    mSettings.writeKernelMappingLPr(ps);
19973                }
19974            }
19975            // can downgrade to reader here
19976            if (writeSettings) {
19977                mSettings.writeLPr();
19978            }
19979        }
19980        return newPkg;
19981    }
19982
19983    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19984            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19985            PackageRemovedInfo outInfo, boolean writeSettings,
19986            PackageParser.Package replacingPackage) {
19987        synchronized (mPackages) {
19988            if (outInfo != null) {
19989                outInfo.uid = ps.appId;
19990            }
19991
19992            if (outInfo != null && outInfo.removedChildPackages != null) {
19993                final int childCount = (ps.childPackageNames != null)
19994                        ? ps.childPackageNames.size() : 0;
19995                for (int i = 0; i < childCount; i++) {
19996                    String childPackageName = ps.childPackageNames.get(i);
19997                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19998                    if (childPs == null) {
19999                        return false;
20000                    }
20001                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
20002                            childPackageName);
20003                    if (childInfo != null) {
20004                        childInfo.uid = childPs.appId;
20005                    }
20006                }
20007            }
20008        }
20009
20010        // Delete package data from internal structures and also remove data if flag is set
20011        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
20012
20013        // Delete the child packages data
20014        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
20015        for (int i = 0; i < childCount; i++) {
20016            PackageSetting childPs;
20017            synchronized (mPackages) {
20018                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
20019            }
20020            if (childPs != null) {
20021                PackageRemovedInfo childOutInfo = (outInfo != null
20022                        && outInfo.removedChildPackages != null)
20023                        ? outInfo.removedChildPackages.get(childPs.name) : null;
20024                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
20025                        && (replacingPackage != null
20026                        && !replacingPackage.hasChildPackage(childPs.name))
20027                        ? flags & ~DELETE_KEEP_DATA : flags;
20028                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
20029                        deleteFlags, writeSettings);
20030            }
20031        }
20032
20033        // Delete application code and resources only for parent packages
20034        if (ps.parentPackageName == null) {
20035            if (deleteCodeAndResources && (outInfo != null)) {
20036                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
20037                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
20038                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
20039            }
20040        }
20041
20042        return true;
20043    }
20044
20045    @Override
20046    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
20047            int userId) {
20048        mContext.enforceCallingOrSelfPermission(
20049                android.Manifest.permission.DELETE_PACKAGES, null);
20050        synchronized (mPackages) {
20051            // Cannot block uninstall of static shared libs as they are
20052            // considered a part of the using app (emulating static linking).
20053            // Also static libs are installed always on internal storage.
20054            PackageParser.Package pkg = mPackages.get(packageName);
20055            if (pkg != null && pkg.staticSharedLibName != null) {
20056                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
20057                        + " providing static shared library: " + pkg.staticSharedLibName);
20058                return false;
20059            }
20060            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
20061            mSettings.writePackageRestrictionsLPr(userId);
20062        }
20063        return true;
20064    }
20065
20066    @Override
20067    public boolean getBlockUninstallForUser(String packageName, int userId) {
20068        synchronized (mPackages) {
20069            final PackageSetting ps = mSettings.mPackages.get(packageName);
20070            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20071                return false;
20072            }
20073            return mSettings.getBlockUninstallLPr(userId, packageName);
20074        }
20075    }
20076
20077    @Override
20078    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20079        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20080        synchronized (mPackages) {
20081            PackageSetting ps = mSettings.mPackages.get(packageName);
20082            if (ps == null) {
20083                Log.w(TAG, "Package doesn't exist: " + packageName);
20084                return false;
20085            }
20086            if (systemUserApp) {
20087                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20088            } else {
20089                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20090            }
20091            mSettings.writeLPr();
20092        }
20093        return true;
20094    }
20095
20096    /*
20097     * This method handles package deletion in general
20098     */
20099    private boolean deletePackageLIF(String packageName, UserHandle user,
20100            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20101            PackageRemovedInfo outInfo, boolean writeSettings,
20102            PackageParser.Package replacingPackage) {
20103        if (packageName == null) {
20104            Slog.w(TAG, "Attempt to delete null packageName.");
20105            return false;
20106        }
20107
20108        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20109
20110        PackageSetting ps;
20111        synchronized (mPackages) {
20112            ps = mSettings.mPackages.get(packageName);
20113            if (ps == null) {
20114                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20115                return false;
20116            }
20117
20118            if (ps.parentPackageName != null && (!isSystemApp(ps)
20119                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20120                if (DEBUG_REMOVE) {
20121                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20122                            + ((user == null) ? UserHandle.USER_ALL : user));
20123                }
20124                final int removedUserId = (user != null) ? user.getIdentifier()
20125                        : UserHandle.USER_ALL;
20126                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20127                    return false;
20128                }
20129                markPackageUninstalledForUserLPw(ps, user);
20130                scheduleWritePackageRestrictionsLocked(user);
20131                return true;
20132            }
20133        }
20134
20135        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20136                && user.getIdentifier() != UserHandle.USER_ALL)) {
20137            // The caller is asking that the package only be deleted for a single
20138            // user.  To do this, we just mark its uninstalled state and delete
20139            // its data. If this is a system app, we only allow this to happen if
20140            // they have set the special DELETE_SYSTEM_APP which requests different
20141            // semantics than normal for uninstalling system apps.
20142            markPackageUninstalledForUserLPw(ps, user);
20143
20144            if (!isSystemApp(ps)) {
20145                // Do not uninstall the APK if an app should be cached
20146                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20147                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20148                    // Other user still have this package installed, so all
20149                    // we need to do is clear this user's data and save that
20150                    // it is uninstalled.
20151                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20152                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20153                        return false;
20154                    }
20155                    scheduleWritePackageRestrictionsLocked(user);
20156                    return true;
20157                } else {
20158                    // We need to set it back to 'installed' so the uninstall
20159                    // broadcasts will be sent correctly.
20160                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20161                    ps.setInstalled(true, user.getIdentifier());
20162                    mSettings.writeKernelMappingLPr(ps);
20163                }
20164            } else {
20165                // This is a system app, so we assume that the
20166                // other users still have this package installed, so all
20167                // we need to do is clear this user's data and save that
20168                // it is uninstalled.
20169                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20170                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20171                    return false;
20172                }
20173                scheduleWritePackageRestrictionsLocked(user);
20174                return true;
20175            }
20176        }
20177
20178        // If we are deleting a composite package for all users, keep track
20179        // of result for each child.
20180        if (ps.childPackageNames != null && outInfo != null) {
20181            synchronized (mPackages) {
20182                final int childCount = ps.childPackageNames.size();
20183                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20184                for (int i = 0; i < childCount; i++) {
20185                    String childPackageName = ps.childPackageNames.get(i);
20186                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20187                    childInfo.removedPackage = childPackageName;
20188                    childInfo.installerPackageName = ps.installerPackageName;
20189                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20190                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20191                    if (childPs != null) {
20192                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20193                    }
20194                }
20195            }
20196        }
20197
20198        boolean ret = false;
20199        if (isSystemApp(ps)) {
20200            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20201            // When an updated system application is deleted we delete the existing resources
20202            // as well and fall back to existing code in system partition
20203            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20204        } else {
20205            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20206            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20207                    outInfo, writeSettings, replacingPackage);
20208        }
20209
20210        // Take a note whether we deleted the package for all users
20211        if (outInfo != null) {
20212            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20213            if (outInfo.removedChildPackages != null) {
20214                synchronized (mPackages) {
20215                    final int childCount = outInfo.removedChildPackages.size();
20216                    for (int i = 0; i < childCount; i++) {
20217                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20218                        if (childInfo != null) {
20219                            childInfo.removedForAllUsers = mPackages.get(
20220                                    childInfo.removedPackage) == null;
20221                        }
20222                    }
20223                }
20224            }
20225            // If we uninstalled an update to a system app there may be some
20226            // child packages that appeared as they are declared in the system
20227            // app but were not declared in the update.
20228            if (isSystemApp(ps)) {
20229                synchronized (mPackages) {
20230                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20231                    final int childCount = (updatedPs.childPackageNames != null)
20232                            ? updatedPs.childPackageNames.size() : 0;
20233                    for (int i = 0; i < childCount; i++) {
20234                        String childPackageName = updatedPs.childPackageNames.get(i);
20235                        if (outInfo.removedChildPackages == null
20236                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20237                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20238                            if (childPs == null) {
20239                                continue;
20240                            }
20241                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20242                            installRes.name = childPackageName;
20243                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20244                            installRes.pkg = mPackages.get(childPackageName);
20245                            installRes.uid = childPs.pkg.applicationInfo.uid;
20246                            if (outInfo.appearedChildPackages == null) {
20247                                outInfo.appearedChildPackages = new ArrayMap<>();
20248                            }
20249                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20250                        }
20251                    }
20252                }
20253            }
20254        }
20255
20256        return ret;
20257    }
20258
20259    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20260        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20261                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20262        for (int nextUserId : userIds) {
20263            if (DEBUG_REMOVE) {
20264                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20265            }
20266            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20267                    false /*installed*/,
20268                    true /*stopped*/,
20269                    true /*notLaunched*/,
20270                    false /*hidden*/,
20271                    false /*suspended*/,
20272                    false /*instantApp*/,
20273                    false /*virtualPreload*/,
20274                    null /*lastDisableAppCaller*/,
20275                    null /*enabledComponents*/,
20276                    null /*disabledComponents*/,
20277                    ps.readUserState(nextUserId).domainVerificationStatus,
20278                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20279        }
20280        mSettings.writeKernelMappingLPr(ps);
20281    }
20282
20283    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20284            PackageRemovedInfo outInfo) {
20285        final PackageParser.Package pkg;
20286        synchronized (mPackages) {
20287            pkg = mPackages.get(ps.name);
20288        }
20289
20290        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20291                : new int[] {userId};
20292        for (int nextUserId : userIds) {
20293            if (DEBUG_REMOVE) {
20294                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20295                        + nextUserId);
20296            }
20297
20298            destroyAppDataLIF(pkg, userId,
20299                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20300            destroyAppProfilesLIF(pkg, userId);
20301            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20302            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20303            schedulePackageCleaning(ps.name, nextUserId, false);
20304            synchronized (mPackages) {
20305                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20306                    scheduleWritePackageRestrictionsLocked(nextUserId);
20307                }
20308                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20309            }
20310        }
20311
20312        if (outInfo != null) {
20313            outInfo.removedPackage = ps.name;
20314            outInfo.installerPackageName = ps.installerPackageName;
20315            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20316            outInfo.removedAppId = ps.appId;
20317            outInfo.removedUsers = userIds;
20318            outInfo.broadcastUsers = userIds;
20319        }
20320
20321        return true;
20322    }
20323
20324    private final class ClearStorageConnection implements ServiceConnection {
20325        IMediaContainerService mContainerService;
20326
20327        @Override
20328        public void onServiceConnected(ComponentName name, IBinder service) {
20329            synchronized (this) {
20330                mContainerService = IMediaContainerService.Stub
20331                        .asInterface(Binder.allowBlocking(service));
20332                notifyAll();
20333            }
20334        }
20335
20336        @Override
20337        public void onServiceDisconnected(ComponentName name) {
20338        }
20339    }
20340
20341    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20342        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20343
20344        final boolean mounted;
20345        if (Environment.isExternalStorageEmulated()) {
20346            mounted = true;
20347        } else {
20348            final String status = Environment.getExternalStorageState();
20349
20350            mounted = status.equals(Environment.MEDIA_MOUNTED)
20351                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20352        }
20353
20354        if (!mounted) {
20355            return;
20356        }
20357
20358        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20359        int[] users;
20360        if (userId == UserHandle.USER_ALL) {
20361            users = sUserManager.getUserIds();
20362        } else {
20363            users = new int[] { userId };
20364        }
20365        final ClearStorageConnection conn = new ClearStorageConnection();
20366        if (mContext.bindServiceAsUser(
20367                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20368            try {
20369                for (int curUser : users) {
20370                    long timeout = SystemClock.uptimeMillis() + 5000;
20371                    synchronized (conn) {
20372                        long now;
20373                        while (conn.mContainerService == null &&
20374                                (now = SystemClock.uptimeMillis()) < timeout) {
20375                            try {
20376                                conn.wait(timeout - now);
20377                            } catch (InterruptedException e) {
20378                            }
20379                        }
20380                    }
20381                    if (conn.mContainerService == null) {
20382                        return;
20383                    }
20384
20385                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20386                    clearDirectory(conn.mContainerService,
20387                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20388                    if (allData) {
20389                        clearDirectory(conn.mContainerService,
20390                                userEnv.buildExternalStorageAppDataDirs(packageName));
20391                        clearDirectory(conn.mContainerService,
20392                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20393                    }
20394                }
20395            } finally {
20396                mContext.unbindService(conn);
20397            }
20398        }
20399    }
20400
20401    @Override
20402    public void clearApplicationProfileData(String packageName) {
20403        enforceSystemOrRoot("Only the system can clear all profile data");
20404
20405        final PackageParser.Package pkg;
20406        synchronized (mPackages) {
20407            pkg = mPackages.get(packageName);
20408        }
20409
20410        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20411            synchronized (mInstallLock) {
20412                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20413            }
20414        }
20415    }
20416
20417    @Override
20418    public void clearApplicationUserData(final String packageName,
20419            final IPackageDataObserver observer, final int userId) {
20420        mContext.enforceCallingOrSelfPermission(
20421                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20422
20423        final int callingUid = Binder.getCallingUid();
20424        enforceCrossUserPermission(callingUid, userId,
20425                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20426
20427        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20428        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20429        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20430            throw new SecurityException("Cannot clear data for a protected package: "
20431                    + packageName);
20432        }
20433        // Queue up an async operation since the package deletion may take a little while.
20434        mHandler.post(new Runnable() {
20435            public void run() {
20436                mHandler.removeCallbacks(this);
20437                final boolean succeeded;
20438                if (!filterApp) {
20439                    try (PackageFreezer freezer = freezePackage(packageName,
20440                            "clearApplicationUserData")) {
20441                        synchronized (mInstallLock) {
20442                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20443                        }
20444                        clearExternalStorageDataSync(packageName, userId, true);
20445                        synchronized (mPackages) {
20446                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20447                                    packageName, userId);
20448                        }
20449                    }
20450                    if (succeeded) {
20451                        // invoke DeviceStorageMonitor's update method to clear any notifications
20452                        DeviceStorageMonitorInternal dsm = LocalServices
20453                                .getService(DeviceStorageMonitorInternal.class);
20454                        if (dsm != null) {
20455                            dsm.checkMemory();
20456                        }
20457                    }
20458                } else {
20459                    succeeded = false;
20460                }
20461                if (observer != null) {
20462                    try {
20463                        observer.onRemoveCompleted(packageName, succeeded);
20464                    } catch (RemoteException e) {
20465                        Log.i(TAG, "Observer no longer exists.");
20466                    }
20467                } //end if observer
20468            } //end run
20469        });
20470    }
20471
20472    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20473        if (packageName == null) {
20474            Slog.w(TAG, "Attempt to delete null packageName.");
20475            return false;
20476        }
20477
20478        // Try finding details about the requested package
20479        PackageParser.Package pkg;
20480        synchronized (mPackages) {
20481            pkg = mPackages.get(packageName);
20482            if (pkg == null) {
20483                final PackageSetting ps = mSettings.mPackages.get(packageName);
20484                if (ps != null) {
20485                    pkg = ps.pkg;
20486                }
20487            }
20488
20489            if (pkg == null) {
20490                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20491                return false;
20492            }
20493
20494            PackageSetting ps = (PackageSetting) pkg.mExtras;
20495            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20496        }
20497
20498        clearAppDataLIF(pkg, userId,
20499                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20500
20501        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20502        removeKeystoreDataIfNeeded(userId, appId);
20503
20504        UserManagerInternal umInternal = getUserManagerInternal();
20505        final int flags;
20506        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20507            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20508        } else if (umInternal.isUserRunning(userId)) {
20509            flags = StorageManager.FLAG_STORAGE_DE;
20510        } else {
20511            flags = 0;
20512        }
20513        prepareAppDataContentsLIF(pkg, userId, flags);
20514
20515        return true;
20516    }
20517
20518    /**
20519     * Reverts user permission state changes (permissions and flags) in
20520     * all packages for a given user.
20521     *
20522     * @param userId The device user for which to do a reset.
20523     */
20524    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20525        final int packageCount = mPackages.size();
20526        for (int i = 0; i < packageCount; i++) {
20527            PackageParser.Package pkg = mPackages.valueAt(i);
20528            PackageSetting ps = (PackageSetting) pkg.mExtras;
20529            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20530        }
20531    }
20532
20533    private void resetNetworkPolicies(int userId) {
20534        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20535    }
20536
20537    /**
20538     * Reverts user permission state changes (permissions and flags).
20539     *
20540     * @param ps The package for which to reset.
20541     * @param userId The device user for which to do a reset.
20542     */
20543    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20544            final PackageSetting ps, final int userId) {
20545        if (ps.pkg == null) {
20546            return;
20547        }
20548
20549        // These are flags that can change base on user actions.
20550        final int userSettableMask = FLAG_PERMISSION_USER_SET
20551                | FLAG_PERMISSION_USER_FIXED
20552                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20553                | FLAG_PERMISSION_REVIEW_REQUIRED;
20554
20555        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20556                | FLAG_PERMISSION_POLICY_FIXED;
20557
20558        boolean writeInstallPermissions = false;
20559        boolean writeRuntimePermissions = false;
20560
20561        final int permissionCount = ps.pkg.requestedPermissions.size();
20562        for (int i = 0; i < permissionCount; i++) {
20563            String permission = ps.pkg.requestedPermissions.get(i);
20564
20565            BasePermission bp = mSettings.mPermissions.get(permission);
20566            if (bp == null) {
20567                continue;
20568            }
20569
20570            // If shared user we just reset the state to which only this app contributed.
20571            if (ps.sharedUser != null) {
20572                boolean used = false;
20573                final int packageCount = ps.sharedUser.packages.size();
20574                for (int j = 0; j < packageCount; j++) {
20575                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20576                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20577                            && pkg.pkg.requestedPermissions.contains(permission)) {
20578                        used = true;
20579                        break;
20580                    }
20581                }
20582                if (used) {
20583                    continue;
20584                }
20585            }
20586
20587            PermissionsState permissionsState = ps.getPermissionsState();
20588
20589            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20590
20591            // Always clear the user settable flags.
20592            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20593                    bp.name) != null;
20594            // If permission review is enabled and this is a legacy app, mark the
20595            // permission as requiring a review as this is the initial state.
20596            int flags = 0;
20597            if (mPermissionReviewRequired
20598                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20599                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20600            }
20601            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20602                if (hasInstallState) {
20603                    writeInstallPermissions = true;
20604                } else {
20605                    writeRuntimePermissions = true;
20606                }
20607            }
20608
20609            // Below is only runtime permission handling.
20610            if (!bp.isRuntime()) {
20611                continue;
20612            }
20613
20614            // Never clobber system or policy.
20615            if ((oldFlags & policyOrSystemFlags) != 0) {
20616                continue;
20617            }
20618
20619            // If this permission was granted by default, make sure it is.
20620            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20621                if (permissionsState.grantRuntimePermission(bp, userId)
20622                        != PERMISSION_OPERATION_FAILURE) {
20623                    writeRuntimePermissions = true;
20624                }
20625            // If permission review is enabled the permissions for a legacy apps
20626            // are represented as constantly granted runtime ones, so don't revoke.
20627            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20628                // Otherwise, reset the permission.
20629                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20630                switch (revokeResult) {
20631                    case PERMISSION_OPERATION_SUCCESS:
20632                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20633                        writeRuntimePermissions = true;
20634                        final int appId = ps.appId;
20635                        mHandler.post(new Runnable() {
20636                            @Override
20637                            public void run() {
20638                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20639                            }
20640                        });
20641                    } break;
20642                }
20643            }
20644        }
20645
20646        // Synchronously write as we are taking permissions away.
20647        if (writeRuntimePermissions) {
20648            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20649        }
20650
20651        // Synchronously write as we are taking permissions away.
20652        if (writeInstallPermissions) {
20653            mSettings.writeLPr();
20654        }
20655    }
20656
20657    /**
20658     * Remove entries from the keystore daemon. Will only remove it if the
20659     * {@code appId} is valid.
20660     */
20661    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20662        if (appId < 0) {
20663            return;
20664        }
20665
20666        final KeyStore keyStore = KeyStore.getInstance();
20667        if (keyStore != null) {
20668            if (userId == UserHandle.USER_ALL) {
20669                for (final int individual : sUserManager.getUserIds()) {
20670                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20671                }
20672            } else {
20673                keyStore.clearUid(UserHandle.getUid(userId, appId));
20674            }
20675        } else {
20676            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20677        }
20678    }
20679
20680    @Override
20681    public void deleteApplicationCacheFiles(final String packageName,
20682            final IPackageDataObserver observer) {
20683        final int userId = UserHandle.getCallingUserId();
20684        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20685    }
20686
20687    @Override
20688    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20689            final IPackageDataObserver observer) {
20690        final int callingUid = Binder.getCallingUid();
20691        mContext.enforceCallingOrSelfPermission(
20692                android.Manifest.permission.DELETE_CACHE_FILES, null);
20693        enforceCrossUserPermission(callingUid, userId,
20694                /* requireFullPermission= */ true, /* checkShell= */ false,
20695                "delete application cache files");
20696        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20697                android.Manifest.permission.ACCESS_INSTANT_APPS);
20698
20699        final PackageParser.Package pkg;
20700        synchronized (mPackages) {
20701            pkg = mPackages.get(packageName);
20702        }
20703
20704        // Queue up an async operation since the package deletion may take a little while.
20705        mHandler.post(new Runnable() {
20706            public void run() {
20707                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20708                boolean doClearData = true;
20709                if (ps != null) {
20710                    final boolean targetIsInstantApp =
20711                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20712                    doClearData = !targetIsInstantApp
20713                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20714                }
20715                if (doClearData) {
20716                    synchronized (mInstallLock) {
20717                        final int flags = StorageManager.FLAG_STORAGE_DE
20718                                | StorageManager.FLAG_STORAGE_CE;
20719                        // We're only clearing cache files, so we don't care if the
20720                        // app is unfrozen and still able to run
20721                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20722                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20723                    }
20724                    clearExternalStorageDataSync(packageName, userId, false);
20725                }
20726                if (observer != null) {
20727                    try {
20728                        observer.onRemoveCompleted(packageName, true);
20729                    } catch (RemoteException e) {
20730                        Log.i(TAG, "Observer no longer exists.");
20731                    }
20732                }
20733            }
20734        });
20735    }
20736
20737    @Override
20738    public void getPackageSizeInfo(final String packageName, int userHandle,
20739            final IPackageStatsObserver observer) {
20740        throw new UnsupportedOperationException(
20741                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20742    }
20743
20744    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20745        final PackageSetting ps;
20746        synchronized (mPackages) {
20747            ps = mSettings.mPackages.get(packageName);
20748            if (ps == null) {
20749                Slog.w(TAG, "Failed to find settings for " + packageName);
20750                return false;
20751            }
20752        }
20753
20754        final String[] packageNames = { packageName };
20755        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20756        final String[] codePaths = { ps.codePathString };
20757
20758        try {
20759            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20760                    ps.appId, ceDataInodes, codePaths, stats);
20761
20762            // For now, ignore code size of packages on system partition
20763            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20764                stats.codeSize = 0;
20765            }
20766
20767            // External clients expect these to be tracked separately
20768            stats.dataSize -= stats.cacheSize;
20769
20770        } catch (InstallerException e) {
20771            Slog.w(TAG, String.valueOf(e));
20772            return false;
20773        }
20774
20775        return true;
20776    }
20777
20778    private int getUidTargetSdkVersionLockedLPr(int uid) {
20779        Object obj = mSettings.getUserIdLPr(uid);
20780        if (obj instanceof SharedUserSetting) {
20781            final SharedUserSetting sus = (SharedUserSetting) obj;
20782            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20783            final Iterator<PackageSetting> it = sus.packages.iterator();
20784            while (it.hasNext()) {
20785                final PackageSetting ps = it.next();
20786                if (ps.pkg != null) {
20787                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20788                    if (v < vers) vers = v;
20789                }
20790            }
20791            return vers;
20792        } else if (obj instanceof PackageSetting) {
20793            final PackageSetting ps = (PackageSetting) obj;
20794            if (ps.pkg != null) {
20795                return ps.pkg.applicationInfo.targetSdkVersion;
20796            }
20797        }
20798        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20799    }
20800
20801    @Override
20802    public void addPreferredActivity(IntentFilter filter, int match,
20803            ComponentName[] set, ComponentName activity, int userId) {
20804        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20805                "Adding preferred");
20806    }
20807
20808    private void addPreferredActivityInternal(IntentFilter filter, int match,
20809            ComponentName[] set, ComponentName activity, boolean always, int userId,
20810            String opname) {
20811        // writer
20812        int callingUid = Binder.getCallingUid();
20813        enforceCrossUserPermission(callingUid, userId,
20814                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20815        if (filter.countActions() == 0) {
20816            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20817            return;
20818        }
20819        synchronized (mPackages) {
20820            if (mContext.checkCallingOrSelfPermission(
20821                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20822                    != PackageManager.PERMISSION_GRANTED) {
20823                if (getUidTargetSdkVersionLockedLPr(callingUid)
20824                        < Build.VERSION_CODES.FROYO) {
20825                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20826                            + callingUid);
20827                    return;
20828                }
20829                mContext.enforceCallingOrSelfPermission(
20830                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20831            }
20832
20833            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20834            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20835                    + userId + ":");
20836            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20837            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20838            scheduleWritePackageRestrictionsLocked(userId);
20839            postPreferredActivityChangedBroadcast(userId);
20840        }
20841    }
20842
20843    private void postPreferredActivityChangedBroadcast(int userId) {
20844        mHandler.post(() -> {
20845            final IActivityManager am = ActivityManager.getService();
20846            if (am == null) {
20847                return;
20848            }
20849
20850            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20851            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20852            try {
20853                am.broadcastIntent(null, intent, null, null,
20854                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20855                        null, false, false, userId);
20856            } catch (RemoteException e) {
20857            }
20858        });
20859    }
20860
20861    @Override
20862    public void replacePreferredActivity(IntentFilter filter, int match,
20863            ComponentName[] set, ComponentName activity, int userId) {
20864        if (filter.countActions() != 1) {
20865            throw new IllegalArgumentException(
20866                    "replacePreferredActivity expects filter to have only 1 action.");
20867        }
20868        if (filter.countDataAuthorities() != 0
20869                || filter.countDataPaths() != 0
20870                || filter.countDataSchemes() > 1
20871                || filter.countDataTypes() != 0) {
20872            throw new IllegalArgumentException(
20873                    "replacePreferredActivity expects filter to have no data authorities, " +
20874                    "paths, or types; and at most one scheme.");
20875        }
20876
20877        final int callingUid = Binder.getCallingUid();
20878        enforceCrossUserPermission(callingUid, userId,
20879                true /* requireFullPermission */, false /* checkShell */,
20880                "replace preferred activity");
20881        synchronized (mPackages) {
20882            if (mContext.checkCallingOrSelfPermission(
20883                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20884                    != PackageManager.PERMISSION_GRANTED) {
20885                if (getUidTargetSdkVersionLockedLPr(callingUid)
20886                        < Build.VERSION_CODES.FROYO) {
20887                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20888                            + Binder.getCallingUid());
20889                    return;
20890                }
20891                mContext.enforceCallingOrSelfPermission(
20892                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20893            }
20894
20895            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20896            if (pir != null) {
20897                // Get all of the existing entries that exactly match this filter.
20898                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20899                if (existing != null && existing.size() == 1) {
20900                    PreferredActivity cur = existing.get(0);
20901                    if (DEBUG_PREFERRED) {
20902                        Slog.i(TAG, "Checking replace of preferred:");
20903                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20904                        if (!cur.mPref.mAlways) {
20905                            Slog.i(TAG, "  -- CUR; not mAlways!");
20906                        } else {
20907                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20908                            Slog.i(TAG, "  -- CUR: mSet="
20909                                    + Arrays.toString(cur.mPref.mSetComponents));
20910                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20911                            Slog.i(TAG, "  -- NEW: mMatch="
20912                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20913                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20914                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20915                        }
20916                    }
20917                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20918                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20919                            && cur.mPref.sameSet(set)) {
20920                        // Setting the preferred activity to what it happens to be already
20921                        if (DEBUG_PREFERRED) {
20922                            Slog.i(TAG, "Replacing with same preferred activity "
20923                                    + cur.mPref.mShortComponent + " for user "
20924                                    + userId + ":");
20925                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20926                        }
20927                        return;
20928                    }
20929                }
20930
20931                if (existing != null) {
20932                    if (DEBUG_PREFERRED) {
20933                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20934                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20935                    }
20936                    for (int i = 0; i < existing.size(); i++) {
20937                        PreferredActivity pa = existing.get(i);
20938                        if (DEBUG_PREFERRED) {
20939                            Slog.i(TAG, "Removing existing preferred activity "
20940                                    + pa.mPref.mComponent + ":");
20941                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20942                        }
20943                        pir.removeFilter(pa);
20944                    }
20945                }
20946            }
20947            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20948                    "Replacing preferred");
20949        }
20950    }
20951
20952    @Override
20953    public void clearPackagePreferredActivities(String packageName) {
20954        final int callingUid = Binder.getCallingUid();
20955        if (getInstantAppPackageName(callingUid) != null) {
20956            return;
20957        }
20958        // writer
20959        synchronized (mPackages) {
20960            PackageParser.Package pkg = mPackages.get(packageName);
20961            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20962                if (mContext.checkCallingOrSelfPermission(
20963                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20964                        != PackageManager.PERMISSION_GRANTED) {
20965                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20966                            < Build.VERSION_CODES.FROYO) {
20967                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20968                                + callingUid);
20969                        return;
20970                    }
20971                    mContext.enforceCallingOrSelfPermission(
20972                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20973                }
20974            }
20975            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20976            if (ps != null
20977                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20978                return;
20979            }
20980            int user = UserHandle.getCallingUserId();
20981            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20982                scheduleWritePackageRestrictionsLocked(user);
20983            }
20984        }
20985    }
20986
20987    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20988    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20989        ArrayList<PreferredActivity> removed = null;
20990        boolean changed = false;
20991        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20992            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20993            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20994            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20995                continue;
20996            }
20997            Iterator<PreferredActivity> it = pir.filterIterator();
20998            while (it.hasNext()) {
20999                PreferredActivity pa = it.next();
21000                // Mark entry for removal only if it matches the package name
21001                // and the entry is of type "always".
21002                if (packageName == null ||
21003                        (pa.mPref.mComponent.getPackageName().equals(packageName)
21004                                && pa.mPref.mAlways)) {
21005                    if (removed == null) {
21006                        removed = new ArrayList<PreferredActivity>();
21007                    }
21008                    removed.add(pa);
21009                }
21010            }
21011            if (removed != null) {
21012                for (int j=0; j<removed.size(); j++) {
21013                    PreferredActivity pa = removed.get(j);
21014                    pir.removeFilter(pa);
21015                }
21016                changed = true;
21017            }
21018        }
21019        if (changed) {
21020            postPreferredActivityChangedBroadcast(userId);
21021        }
21022        return changed;
21023    }
21024
21025    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21026    private void clearIntentFilterVerificationsLPw(int userId) {
21027        final int packageCount = mPackages.size();
21028        for (int i = 0; i < packageCount; i++) {
21029            PackageParser.Package pkg = mPackages.valueAt(i);
21030            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
21031        }
21032    }
21033
21034    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21035    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
21036        if (userId == UserHandle.USER_ALL) {
21037            if (mSettings.removeIntentFilterVerificationLPw(packageName,
21038                    sUserManager.getUserIds())) {
21039                for (int oneUserId : sUserManager.getUserIds()) {
21040                    scheduleWritePackageRestrictionsLocked(oneUserId);
21041                }
21042            }
21043        } else {
21044            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
21045                scheduleWritePackageRestrictionsLocked(userId);
21046            }
21047        }
21048    }
21049
21050    /** Clears state for all users, and touches intent filter verification policy */
21051    void clearDefaultBrowserIfNeeded(String packageName) {
21052        for (int oneUserId : sUserManager.getUserIds()) {
21053            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
21054        }
21055    }
21056
21057    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
21058        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
21059        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
21060            if (packageName.equals(defaultBrowserPackageName)) {
21061                setDefaultBrowserPackageName(null, userId);
21062            }
21063        }
21064    }
21065
21066    @Override
21067    public void resetApplicationPreferences(int userId) {
21068        mContext.enforceCallingOrSelfPermission(
21069                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21070        final long identity = Binder.clearCallingIdentity();
21071        // writer
21072        try {
21073            synchronized (mPackages) {
21074                clearPackagePreferredActivitiesLPw(null, userId);
21075                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21076                // TODO: We have to reset the default SMS and Phone. This requires
21077                // significant refactoring to keep all default apps in the package
21078                // manager (cleaner but more work) or have the services provide
21079                // callbacks to the package manager to request a default app reset.
21080                applyFactoryDefaultBrowserLPw(userId);
21081                clearIntentFilterVerificationsLPw(userId);
21082                primeDomainVerificationsLPw(userId);
21083                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21084                scheduleWritePackageRestrictionsLocked(userId);
21085            }
21086            resetNetworkPolicies(userId);
21087        } finally {
21088            Binder.restoreCallingIdentity(identity);
21089        }
21090    }
21091
21092    @Override
21093    public int getPreferredActivities(List<IntentFilter> outFilters,
21094            List<ComponentName> outActivities, String packageName) {
21095        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21096            return 0;
21097        }
21098        int num = 0;
21099        final int userId = UserHandle.getCallingUserId();
21100        // reader
21101        synchronized (mPackages) {
21102            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21103            if (pir != null) {
21104                final Iterator<PreferredActivity> it = pir.filterIterator();
21105                while (it.hasNext()) {
21106                    final PreferredActivity pa = it.next();
21107                    if (packageName == null
21108                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21109                                    && pa.mPref.mAlways)) {
21110                        if (outFilters != null) {
21111                            outFilters.add(new IntentFilter(pa));
21112                        }
21113                        if (outActivities != null) {
21114                            outActivities.add(pa.mPref.mComponent);
21115                        }
21116                    }
21117                }
21118            }
21119        }
21120
21121        return num;
21122    }
21123
21124    @Override
21125    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21126            int userId) {
21127        int callingUid = Binder.getCallingUid();
21128        if (callingUid != Process.SYSTEM_UID) {
21129            throw new SecurityException(
21130                    "addPersistentPreferredActivity can only be run by the system");
21131        }
21132        if (filter.countActions() == 0) {
21133            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21134            return;
21135        }
21136        synchronized (mPackages) {
21137            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21138                    ":");
21139            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21140            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21141                    new PersistentPreferredActivity(filter, activity));
21142            scheduleWritePackageRestrictionsLocked(userId);
21143            postPreferredActivityChangedBroadcast(userId);
21144        }
21145    }
21146
21147    @Override
21148    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21149        int callingUid = Binder.getCallingUid();
21150        if (callingUid != Process.SYSTEM_UID) {
21151            throw new SecurityException(
21152                    "clearPackagePersistentPreferredActivities can only be run by the system");
21153        }
21154        ArrayList<PersistentPreferredActivity> removed = null;
21155        boolean changed = false;
21156        synchronized (mPackages) {
21157            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21158                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21159                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21160                        .valueAt(i);
21161                if (userId != thisUserId) {
21162                    continue;
21163                }
21164                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21165                while (it.hasNext()) {
21166                    PersistentPreferredActivity ppa = it.next();
21167                    // Mark entry for removal only if it matches the package name.
21168                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21169                        if (removed == null) {
21170                            removed = new ArrayList<PersistentPreferredActivity>();
21171                        }
21172                        removed.add(ppa);
21173                    }
21174                }
21175                if (removed != null) {
21176                    for (int j=0; j<removed.size(); j++) {
21177                        PersistentPreferredActivity ppa = removed.get(j);
21178                        ppir.removeFilter(ppa);
21179                    }
21180                    changed = true;
21181                }
21182            }
21183
21184            if (changed) {
21185                scheduleWritePackageRestrictionsLocked(userId);
21186                postPreferredActivityChangedBroadcast(userId);
21187            }
21188        }
21189    }
21190
21191    /**
21192     * Common machinery for picking apart a restored XML blob and passing
21193     * it to a caller-supplied functor to be applied to the running system.
21194     */
21195    private void restoreFromXml(XmlPullParser parser, int userId,
21196            String expectedStartTag, BlobXmlRestorer functor)
21197            throws IOException, XmlPullParserException {
21198        int type;
21199        while ((type = parser.next()) != XmlPullParser.START_TAG
21200                && type != XmlPullParser.END_DOCUMENT) {
21201        }
21202        if (type != XmlPullParser.START_TAG) {
21203            // oops didn't find a start tag?!
21204            if (DEBUG_BACKUP) {
21205                Slog.e(TAG, "Didn't find start tag during restore");
21206            }
21207            return;
21208        }
21209Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21210        // this is supposed to be TAG_PREFERRED_BACKUP
21211        if (!expectedStartTag.equals(parser.getName())) {
21212            if (DEBUG_BACKUP) {
21213                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21214            }
21215            return;
21216        }
21217
21218        // skip interfering stuff, then we're aligned with the backing implementation
21219        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21220Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21221        functor.apply(parser, userId);
21222    }
21223
21224    private interface BlobXmlRestorer {
21225        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21226    }
21227
21228    /**
21229     * Non-Binder method, support for the backup/restore mechanism: write the
21230     * full set of preferred activities in its canonical XML format.  Returns the
21231     * XML output as a byte array, or null if there is none.
21232     */
21233    @Override
21234    public byte[] getPreferredActivityBackup(int userId) {
21235        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21236            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21237        }
21238
21239        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21240        try {
21241            final XmlSerializer serializer = new FastXmlSerializer();
21242            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21243            serializer.startDocument(null, true);
21244            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21245
21246            synchronized (mPackages) {
21247                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21248            }
21249
21250            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21251            serializer.endDocument();
21252            serializer.flush();
21253        } catch (Exception e) {
21254            if (DEBUG_BACKUP) {
21255                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21256            }
21257            return null;
21258        }
21259
21260        return dataStream.toByteArray();
21261    }
21262
21263    @Override
21264    public void restorePreferredActivities(byte[] backup, int userId) {
21265        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21266            throw new SecurityException("Only the system may call restorePreferredActivities()");
21267        }
21268
21269        try {
21270            final XmlPullParser parser = Xml.newPullParser();
21271            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21272            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21273                    new BlobXmlRestorer() {
21274                        @Override
21275                        public void apply(XmlPullParser parser, int userId)
21276                                throws XmlPullParserException, IOException {
21277                            synchronized (mPackages) {
21278                                mSettings.readPreferredActivitiesLPw(parser, userId);
21279                            }
21280                        }
21281                    } );
21282        } catch (Exception e) {
21283            if (DEBUG_BACKUP) {
21284                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21285            }
21286        }
21287    }
21288
21289    /**
21290     * Non-Binder method, support for the backup/restore mechanism: write the
21291     * default browser (etc) settings in its canonical XML format.  Returns the default
21292     * browser XML representation as a byte array, or null if there is none.
21293     */
21294    @Override
21295    public byte[] getDefaultAppsBackup(int userId) {
21296        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21297            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21298        }
21299
21300        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21301        try {
21302            final XmlSerializer serializer = new FastXmlSerializer();
21303            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21304            serializer.startDocument(null, true);
21305            serializer.startTag(null, TAG_DEFAULT_APPS);
21306
21307            synchronized (mPackages) {
21308                mSettings.writeDefaultAppsLPr(serializer, userId);
21309            }
21310
21311            serializer.endTag(null, TAG_DEFAULT_APPS);
21312            serializer.endDocument();
21313            serializer.flush();
21314        } catch (Exception e) {
21315            if (DEBUG_BACKUP) {
21316                Slog.e(TAG, "Unable to write default apps for backup", e);
21317            }
21318            return null;
21319        }
21320
21321        return dataStream.toByteArray();
21322    }
21323
21324    @Override
21325    public void restoreDefaultApps(byte[] backup, int userId) {
21326        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21327            throw new SecurityException("Only the system may call restoreDefaultApps()");
21328        }
21329
21330        try {
21331            final XmlPullParser parser = Xml.newPullParser();
21332            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21333            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21334                    new BlobXmlRestorer() {
21335                        @Override
21336                        public void apply(XmlPullParser parser, int userId)
21337                                throws XmlPullParserException, IOException {
21338                            synchronized (mPackages) {
21339                                mSettings.readDefaultAppsLPw(parser, userId);
21340                            }
21341                        }
21342                    } );
21343        } catch (Exception e) {
21344            if (DEBUG_BACKUP) {
21345                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21346            }
21347        }
21348    }
21349
21350    @Override
21351    public byte[] getIntentFilterVerificationBackup(int userId) {
21352        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21353            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21354        }
21355
21356        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21357        try {
21358            final XmlSerializer serializer = new FastXmlSerializer();
21359            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21360            serializer.startDocument(null, true);
21361            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21362
21363            synchronized (mPackages) {
21364                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21365            }
21366
21367            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21368            serializer.endDocument();
21369            serializer.flush();
21370        } catch (Exception e) {
21371            if (DEBUG_BACKUP) {
21372                Slog.e(TAG, "Unable to write default apps for backup", e);
21373            }
21374            return null;
21375        }
21376
21377        return dataStream.toByteArray();
21378    }
21379
21380    @Override
21381    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21382        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21383            throw new SecurityException("Only the system may call restorePreferredActivities()");
21384        }
21385
21386        try {
21387            final XmlPullParser parser = Xml.newPullParser();
21388            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21389            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21390                    new BlobXmlRestorer() {
21391                        @Override
21392                        public void apply(XmlPullParser parser, int userId)
21393                                throws XmlPullParserException, IOException {
21394                            synchronized (mPackages) {
21395                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21396                                mSettings.writeLPr();
21397                            }
21398                        }
21399                    } );
21400        } catch (Exception e) {
21401            if (DEBUG_BACKUP) {
21402                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21403            }
21404        }
21405    }
21406
21407    @Override
21408    public byte[] getPermissionGrantBackup(int userId) {
21409        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21410            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21411        }
21412
21413        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21414        try {
21415            final XmlSerializer serializer = new FastXmlSerializer();
21416            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21417            serializer.startDocument(null, true);
21418            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21419
21420            synchronized (mPackages) {
21421                serializeRuntimePermissionGrantsLPr(serializer, userId);
21422            }
21423
21424            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21425            serializer.endDocument();
21426            serializer.flush();
21427        } catch (Exception e) {
21428            if (DEBUG_BACKUP) {
21429                Slog.e(TAG, "Unable to write default apps for backup", e);
21430            }
21431            return null;
21432        }
21433
21434        return dataStream.toByteArray();
21435    }
21436
21437    @Override
21438    public void restorePermissionGrants(byte[] backup, int userId) {
21439        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21440            throw new SecurityException("Only the system may call restorePermissionGrants()");
21441        }
21442
21443        try {
21444            final XmlPullParser parser = Xml.newPullParser();
21445            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21446            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21447                    new BlobXmlRestorer() {
21448                        @Override
21449                        public void apply(XmlPullParser parser, int userId)
21450                                throws XmlPullParserException, IOException {
21451                            synchronized (mPackages) {
21452                                processRestoredPermissionGrantsLPr(parser, userId);
21453                            }
21454                        }
21455                    } );
21456        } catch (Exception e) {
21457            if (DEBUG_BACKUP) {
21458                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21459            }
21460        }
21461    }
21462
21463    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21464            throws IOException {
21465        serializer.startTag(null, TAG_ALL_GRANTS);
21466
21467        final int N = mSettings.mPackages.size();
21468        for (int i = 0; i < N; i++) {
21469            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21470            boolean pkgGrantsKnown = false;
21471
21472            PermissionsState packagePerms = ps.getPermissionsState();
21473
21474            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21475                final int grantFlags = state.getFlags();
21476                // only look at grants that are not system/policy fixed
21477                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21478                    final boolean isGranted = state.isGranted();
21479                    // And only back up the user-twiddled state bits
21480                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21481                        final String packageName = mSettings.mPackages.keyAt(i);
21482                        if (!pkgGrantsKnown) {
21483                            serializer.startTag(null, TAG_GRANT);
21484                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21485                            pkgGrantsKnown = true;
21486                        }
21487
21488                        final boolean userSet =
21489                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21490                        final boolean userFixed =
21491                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21492                        final boolean revoke =
21493                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21494
21495                        serializer.startTag(null, TAG_PERMISSION);
21496                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21497                        if (isGranted) {
21498                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21499                        }
21500                        if (userSet) {
21501                            serializer.attribute(null, ATTR_USER_SET, "true");
21502                        }
21503                        if (userFixed) {
21504                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21505                        }
21506                        if (revoke) {
21507                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21508                        }
21509                        serializer.endTag(null, TAG_PERMISSION);
21510                    }
21511                }
21512            }
21513
21514            if (pkgGrantsKnown) {
21515                serializer.endTag(null, TAG_GRANT);
21516            }
21517        }
21518
21519        serializer.endTag(null, TAG_ALL_GRANTS);
21520    }
21521
21522    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21523            throws XmlPullParserException, IOException {
21524        String pkgName = null;
21525        int outerDepth = parser.getDepth();
21526        int type;
21527        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21528                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21529            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21530                continue;
21531            }
21532
21533            final String tagName = parser.getName();
21534            if (tagName.equals(TAG_GRANT)) {
21535                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21536                if (DEBUG_BACKUP) {
21537                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21538                }
21539            } else if (tagName.equals(TAG_PERMISSION)) {
21540
21541                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21542                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21543
21544                int newFlagSet = 0;
21545                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21546                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21547                }
21548                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21549                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21550                }
21551                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21552                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21553                }
21554                if (DEBUG_BACKUP) {
21555                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21556                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21557                }
21558                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21559                if (ps != null) {
21560                    // Already installed so we apply the grant immediately
21561                    if (DEBUG_BACKUP) {
21562                        Slog.v(TAG, "        + already installed; applying");
21563                    }
21564                    PermissionsState perms = ps.getPermissionsState();
21565                    BasePermission bp = mSettings.mPermissions.get(permName);
21566                    if (bp != null) {
21567                        if (isGranted) {
21568                            perms.grantRuntimePermission(bp, userId);
21569                        }
21570                        if (newFlagSet != 0) {
21571                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21572                        }
21573                    }
21574                } else {
21575                    // Need to wait for post-restore install to apply the grant
21576                    if (DEBUG_BACKUP) {
21577                        Slog.v(TAG, "        - not yet installed; saving for later");
21578                    }
21579                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21580                            isGranted, newFlagSet, userId);
21581                }
21582            } else {
21583                PackageManagerService.reportSettingsProblem(Log.WARN,
21584                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21585                XmlUtils.skipCurrentTag(parser);
21586            }
21587        }
21588
21589        scheduleWriteSettingsLocked();
21590        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21591    }
21592
21593    @Override
21594    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21595            int sourceUserId, int targetUserId, int flags) {
21596        mContext.enforceCallingOrSelfPermission(
21597                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21598        int callingUid = Binder.getCallingUid();
21599        enforceOwnerRights(ownerPackage, callingUid);
21600        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21601        if (intentFilter.countActions() == 0) {
21602            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21603            return;
21604        }
21605        synchronized (mPackages) {
21606            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21607                    ownerPackage, targetUserId, flags);
21608            CrossProfileIntentResolver resolver =
21609                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21610            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21611            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21612            if (existing != null) {
21613                int size = existing.size();
21614                for (int i = 0; i < size; i++) {
21615                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21616                        return;
21617                    }
21618                }
21619            }
21620            resolver.addFilter(newFilter);
21621            scheduleWritePackageRestrictionsLocked(sourceUserId);
21622        }
21623    }
21624
21625    @Override
21626    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21627        mContext.enforceCallingOrSelfPermission(
21628                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21629        final int callingUid = Binder.getCallingUid();
21630        enforceOwnerRights(ownerPackage, callingUid);
21631        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21632        synchronized (mPackages) {
21633            CrossProfileIntentResolver resolver =
21634                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21635            ArraySet<CrossProfileIntentFilter> set =
21636                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21637            for (CrossProfileIntentFilter filter : set) {
21638                if (filter.getOwnerPackage().equals(ownerPackage)) {
21639                    resolver.removeFilter(filter);
21640                }
21641            }
21642            scheduleWritePackageRestrictionsLocked(sourceUserId);
21643        }
21644    }
21645
21646    // Enforcing that callingUid is owning pkg on userId
21647    private void enforceOwnerRights(String pkg, int callingUid) {
21648        // The system owns everything.
21649        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21650            return;
21651        }
21652        final int callingUserId = UserHandle.getUserId(callingUid);
21653        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21654        if (pi == null) {
21655            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21656                    + callingUserId);
21657        }
21658        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21659            throw new SecurityException("Calling uid " + callingUid
21660                    + " does not own package " + pkg);
21661        }
21662    }
21663
21664    @Override
21665    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21666        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21667            return null;
21668        }
21669        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21670    }
21671
21672    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21673        UserManagerService ums = UserManagerService.getInstance();
21674        if (ums != null) {
21675            final UserInfo parent = ums.getProfileParent(userId);
21676            final int launcherUid = (parent != null) ? parent.id : userId;
21677            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21678            if (launcherComponent != null) {
21679                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21680                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21681                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21682                        .setPackage(launcherComponent.getPackageName());
21683                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21684            }
21685        }
21686    }
21687
21688    /**
21689     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21690     * then reports the most likely home activity or null if there are more than one.
21691     */
21692    private ComponentName getDefaultHomeActivity(int userId) {
21693        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21694        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21695        if (cn != null) {
21696            return cn;
21697        }
21698
21699        // Find the launcher with the highest priority and return that component if there are no
21700        // other home activity with the same priority.
21701        int lastPriority = Integer.MIN_VALUE;
21702        ComponentName lastComponent = null;
21703        final int size = allHomeCandidates.size();
21704        for (int i = 0; i < size; i++) {
21705            final ResolveInfo ri = allHomeCandidates.get(i);
21706            if (ri.priority > lastPriority) {
21707                lastComponent = ri.activityInfo.getComponentName();
21708                lastPriority = ri.priority;
21709            } else if (ri.priority == lastPriority) {
21710                // Two components found with same priority.
21711                lastComponent = null;
21712            }
21713        }
21714        return lastComponent;
21715    }
21716
21717    private Intent getHomeIntent() {
21718        Intent intent = new Intent(Intent.ACTION_MAIN);
21719        intent.addCategory(Intent.CATEGORY_HOME);
21720        intent.addCategory(Intent.CATEGORY_DEFAULT);
21721        return intent;
21722    }
21723
21724    private IntentFilter getHomeFilter() {
21725        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21726        filter.addCategory(Intent.CATEGORY_HOME);
21727        filter.addCategory(Intent.CATEGORY_DEFAULT);
21728        return filter;
21729    }
21730
21731    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21732            int userId) {
21733        Intent intent  = getHomeIntent();
21734        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21735                PackageManager.GET_META_DATA, userId);
21736        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21737                true, false, false, userId);
21738
21739        allHomeCandidates.clear();
21740        if (list != null) {
21741            for (ResolveInfo ri : list) {
21742                allHomeCandidates.add(ri);
21743            }
21744        }
21745        return (preferred == null || preferred.activityInfo == null)
21746                ? null
21747                : new ComponentName(preferred.activityInfo.packageName,
21748                        preferred.activityInfo.name);
21749    }
21750
21751    @Override
21752    public void setHomeActivity(ComponentName comp, int userId) {
21753        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21754            return;
21755        }
21756        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21757        getHomeActivitiesAsUser(homeActivities, userId);
21758
21759        boolean found = false;
21760
21761        final int size = homeActivities.size();
21762        final ComponentName[] set = new ComponentName[size];
21763        for (int i = 0; i < size; i++) {
21764            final ResolveInfo candidate = homeActivities.get(i);
21765            final ActivityInfo info = candidate.activityInfo;
21766            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21767            set[i] = activityName;
21768            if (!found && activityName.equals(comp)) {
21769                found = true;
21770            }
21771        }
21772        if (!found) {
21773            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21774                    + userId);
21775        }
21776        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21777                set, comp, userId);
21778    }
21779
21780    private @Nullable String getSetupWizardPackageName() {
21781        final Intent intent = new Intent(Intent.ACTION_MAIN);
21782        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21783
21784        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21785                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21786                        | MATCH_DISABLED_COMPONENTS,
21787                UserHandle.myUserId());
21788        if (matches.size() == 1) {
21789            return matches.get(0).getComponentInfo().packageName;
21790        } else {
21791            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21792                    + ": matches=" + matches);
21793            return null;
21794        }
21795    }
21796
21797    private @Nullable String getStorageManagerPackageName() {
21798        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21799
21800        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21801                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21802                        | MATCH_DISABLED_COMPONENTS,
21803                UserHandle.myUserId());
21804        if (matches.size() == 1) {
21805            return matches.get(0).getComponentInfo().packageName;
21806        } else {
21807            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21808                    + matches.size() + ": matches=" + matches);
21809            return null;
21810        }
21811    }
21812
21813    @Override
21814    public void setApplicationEnabledSetting(String appPackageName,
21815            int newState, int flags, int userId, String callingPackage) {
21816        if (!sUserManager.exists(userId)) return;
21817        if (callingPackage == null) {
21818            callingPackage = Integer.toString(Binder.getCallingUid());
21819        }
21820        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21821    }
21822
21823    @Override
21824    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21825        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21826        synchronized (mPackages) {
21827            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21828            if (pkgSetting != null) {
21829                pkgSetting.setUpdateAvailable(updateAvailable);
21830            }
21831        }
21832    }
21833
21834    @Override
21835    public void setComponentEnabledSetting(ComponentName componentName,
21836            int newState, int flags, int userId) {
21837        if (!sUserManager.exists(userId)) return;
21838        setEnabledSetting(componentName.getPackageName(),
21839                componentName.getClassName(), newState, flags, userId, null);
21840    }
21841
21842    private void setEnabledSetting(final String packageName, String className, int newState,
21843            final int flags, int userId, String callingPackage) {
21844        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21845              || newState == COMPONENT_ENABLED_STATE_ENABLED
21846              || newState == COMPONENT_ENABLED_STATE_DISABLED
21847              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21848              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21849            throw new IllegalArgumentException("Invalid new component state: "
21850                    + newState);
21851        }
21852        PackageSetting pkgSetting;
21853        final int callingUid = Binder.getCallingUid();
21854        final int permission;
21855        if (callingUid == Process.SYSTEM_UID) {
21856            permission = PackageManager.PERMISSION_GRANTED;
21857        } else {
21858            permission = mContext.checkCallingOrSelfPermission(
21859                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21860        }
21861        enforceCrossUserPermission(callingUid, userId,
21862                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21863        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21864        boolean sendNow = false;
21865        boolean isApp = (className == null);
21866        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21867        String componentName = isApp ? packageName : className;
21868        int packageUid = -1;
21869        ArrayList<String> components;
21870
21871        // reader
21872        synchronized (mPackages) {
21873            pkgSetting = mSettings.mPackages.get(packageName);
21874            if (pkgSetting == null) {
21875                if (!isCallerInstantApp) {
21876                    if (className == null) {
21877                        throw new IllegalArgumentException("Unknown package: " + packageName);
21878                    }
21879                    throw new IllegalArgumentException(
21880                            "Unknown component: " + packageName + "/" + className);
21881                } else {
21882                    // throw SecurityException to prevent leaking package information
21883                    throw new SecurityException(
21884                            "Attempt to change component state; "
21885                            + "pid=" + Binder.getCallingPid()
21886                            + ", uid=" + callingUid
21887                            + (className == null
21888                                    ? ", package=" + packageName
21889                                    : ", component=" + packageName + "/" + className));
21890                }
21891            }
21892        }
21893
21894        // Limit who can change which apps
21895        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21896            // Don't allow apps that don't have permission to modify other apps
21897            if (!allowedByPermission
21898                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21899                throw new SecurityException(
21900                        "Attempt to change component state; "
21901                        + "pid=" + Binder.getCallingPid()
21902                        + ", uid=" + callingUid
21903                        + (className == null
21904                                ? ", package=" + packageName
21905                                : ", component=" + packageName + "/" + className));
21906            }
21907            // Don't allow changing protected packages.
21908            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21909                throw new SecurityException("Cannot disable a protected package: " + packageName);
21910            }
21911        }
21912
21913        synchronized (mPackages) {
21914            if (callingUid == Process.SHELL_UID
21915                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21916                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21917                // unless it is a test package.
21918                int oldState = pkgSetting.getEnabled(userId);
21919                if (className == null
21920                        &&
21921                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21922                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21923                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21924                        &&
21925                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21926                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21927                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21928                    // ok
21929                } else {
21930                    throw new SecurityException(
21931                            "Shell cannot change component state for " + packageName + "/"
21932                                    + className + " to " + newState);
21933                }
21934            }
21935        }
21936        if (className == null) {
21937            // We're dealing with an application/package level state change
21938            synchronized (mPackages) {
21939                if (pkgSetting.getEnabled(userId) == newState) {
21940                    // Nothing to do
21941                    return;
21942                }
21943            }
21944            // If we're enabling a system stub, there's a little more work to do.
21945            // Prior to enabling the package, we need to decompress the APK(s) to the
21946            // data partition and then replace the version on the system partition.
21947            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21948            final boolean isSystemStub = deletedPkg.isStub
21949                    && deletedPkg.isSystemApp();
21950            if (isSystemStub
21951                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21952                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21953                final File codePath = decompressPackage(deletedPkg);
21954                if (codePath == null) {
21955                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21956                    return;
21957                }
21958                // TODO remove direct parsing of the package object during internal cleanup
21959                // of scan package
21960                // We need to call parse directly here for no other reason than we need
21961                // the new package in order to disable the old one [we use the information
21962                // for some internal optimization to optionally create a new package setting
21963                // object on replace]. However, we can't get the package from the scan
21964                // because the scan modifies live structures and we need to remove the
21965                // old [system] package from the system before a scan can be attempted.
21966                // Once scan is indempotent we can remove this parse and use the package
21967                // object we scanned, prior to adding it to package settings.
21968                final PackageParser pp = new PackageParser();
21969                pp.setSeparateProcesses(mSeparateProcesses);
21970                pp.setDisplayMetrics(mMetrics);
21971                pp.setCallback(mPackageParserCallback);
21972                final PackageParser.Package tmpPkg;
21973                try {
21974                    final int parseFlags = mDefParseFlags
21975                            | PackageParser.PARSE_MUST_BE_APK
21976                            | PackageParser.PARSE_IS_SYSTEM
21977                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21978                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21979                } catch (PackageParserException e) {
21980                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21981                    return;
21982                }
21983                synchronized (mInstallLock) {
21984                    // Disable the stub and remove any package entries
21985                    removePackageLI(deletedPkg, true);
21986                    synchronized (mPackages) {
21987                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21988                    }
21989                    final PackageParser.Package newPkg;
21990                    try (PackageFreezer freezer =
21991                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21992                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21993                                | PackageParser.PARSE_ENFORCE_CODE;
21994                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21995                                0 /*currentTime*/, null /*user*/);
21996                        prepareAppDataAfterInstallLIF(newPkg);
21997                        synchronized (mPackages) {
21998                            try {
21999                                updateSharedLibrariesLPr(newPkg, null);
22000                            } catch (PackageManagerException e) {
22001                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
22002                            }
22003                            updatePermissionsLPw(newPkg.packageName, newPkg,
22004                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
22005                            mSettings.writeLPr();
22006                        }
22007                    } catch (PackageManagerException e) {
22008                        // Whoops! Something went wrong; try to roll back to the stub
22009                        Slog.w(TAG, "Failed to install compressed system package:"
22010                                + pkgSetting.name, e);
22011                        // Remove the failed install
22012                        removeCodePathLI(codePath);
22013
22014                        // Install the system package
22015                        try (PackageFreezer freezer =
22016                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22017                            synchronized (mPackages) {
22018                                // NOTE: The system package always needs to be enabled; even
22019                                // if it's for a compressed stub. If we don't, installing the
22020                                // system package fails during scan [scanning checks the disabled
22021                                // packages]. We will reverse this later, after we've "installed"
22022                                // the stub.
22023                                // This leaves us in a fragile state; the stub should never be
22024                                // enabled, so, cross your fingers and hope nothing goes wrong
22025                                // until we can disable the package later.
22026                                enableSystemPackageLPw(deletedPkg);
22027                            }
22028                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
22029                                    false /*isPrivileged*/, null /*allUserHandles*/,
22030                                    null /*origUserHandles*/, null /*origPermissionsState*/,
22031                                    true /*writeSettings*/);
22032                        } catch (PackageManagerException pme) {
22033                            Slog.w(TAG, "Failed to restore system package:"
22034                                    + deletedPkg.packageName, pme);
22035                        } finally {
22036                            synchronized (mPackages) {
22037                                mSettings.disableSystemPackageLPw(
22038                                        deletedPkg.packageName, true /*replaced*/);
22039                                mSettings.writeLPr();
22040                            }
22041                        }
22042                        return;
22043                    }
22044                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
22045                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22046                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
22047                    mDexManager.notifyPackageUpdated(newPkg.packageName,
22048                            newPkg.baseCodePath, newPkg.splitCodePaths);
22049                }
22050            }
22051            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22052                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
22053                // Don't care about who enables an app.
22054                callingPackage = null;
22055            }
22056            synchronized (mPackages) {
22057                pkgSetting.setEnabled(newState, userId, callingPackage);
22058            }
22059        } else {
22060            synchronized (mPackages) {
22061                // We're dealing with a component level state change
22062                // First, verify that this is a valid class name.
22063                PackageParser.Package pkg = pkgSetting.pkg;
22064                if (pkg == null || !pkg.hasComponentClassName(className)) {
22065                    if (pkg != null &&
22066                            pkg.applicationInfo.targetSdkVersion >=
22067                                    Build.VERSION_CODES.JELLY_BEAN) {
22068                        throw new IllegalArgumentException("Component class " + className
22069                                + " does not exist in " + packageName);
22070                    } else {
22071                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22072                                + className + " does not exist in " + packageName);
22073                    }
22074                }
22075                switch (newState) {
22076                    case COMPONENT_ENABLED_STATE_ENABLED:
22077                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22078                            return;
22079                        }
22080                        break;
22081                    case COMPONENT_ENABLED_STATE_DISABLED:
22082                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22083                            return;
22084                        }
22085                        break;
22086                    case COMPONENT_ENABLED_STATE_DEFAULT:
22087                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22088                            return;
22089                        }
22090                        break;
22091                    default:
22092                        Slog.e(TAG, "Invalid new component state: " + newState);
22093                        return;
22094                }
22095            }
22096        }
22097        synchronized (mPackages) {
22098            scheduleWritePackageRestrictionsLocked(userId);
22099            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22100            final long callingId = Binder.clearCallingIdentity();
22101            try {
22102                updateInstantAppInstallerLocked(packageName);
22103            } finally {
22104                Binder.restoreCallingIdentity(callingId);
22105            }
22106            components = mPendingBroadcasts.get(userId, packageName);
22107            final boolean newPackage = components == null;
22108            if (newPackage) {
22109                components = new ArrayList<String>();
22110            }
22111            if (!components.contains(componentName)) {
22112                components.add(componentName);
22113            }
22114            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22115                sendNow = true;
22116                // Purge entry from pending broadcast list if another one exists already
22117                // since we are sending one right away.
22118                mPendingBroadcasts.remove(userId, packageName);
22119            } else {
22120                if (newPackage) {
22121                    mPendingBroadcasts.put(userId, packageName, components);
22122                }
22123                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22124                    // Schedule a message
22125                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22126                }
22127            }
22128        }
22129
22130        long callingId = Binder.clearCallingIdentity();
22131        try {
22132            if (sendNow) {
22133                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22134                sendPackageChangedBroadcast(packageName,
22135                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22136            }
22137        } finally {
22138            Binder.restoreCallingIdentity(callingId);
22139        }
22140    }
22141
22142    @Override
22143    public void flushPackageRestrictionsAsUser(int userId) {
22144        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22145            return;
22146        }
22147        if (!sUserManager.exists(userId)) {
22148            return;
22149        }
22150        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22151                false /* checkShell */, "flushPackageRestrictions");
22152        synchronized (mPackages) {
22153            mSettings.writePackageRestrictionsLPr(userId);
22154            mDirtyUsers.remove(userId);
22155            if (mDirtyUsers.isEmpty()) {
22156                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22157            }
22158        }
22159    }
22160
22161    private void sendPackageChangedBroadcast(String packageName,
22162            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22163        if (DEBUG_INSTALL)
22164            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22165                    + componentNames);
22166        Bundle extras = new Bundle(4);
22167        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22168        String nameList[] = new String[componentNames.size()];
22169        componentNames.toArray(nameList);
22170        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22171        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22172        extras.putInt(Intent.EXTRA_UID, packageUid);
22173        // If this is not reporting a change of the overall package, then only send it
22174        // to registered receivers.  We don't want to launch a swath of apps for every
22175        // little component state change.
22176        final int flags = !componentNames.contains(packageName)
22177                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22178        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22179                new int[] {UserHandle.getUserId(packageUid)});
22180    }
22181
22182    @Override
22183    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22184        if (!sUserManager.exists(userId)) return;
22185        final int callingUid = Binder.getCallingUid();
22186        if (getInstantAppPackageName(callingUid) != null) {
22187            return;
22188        }
22189        final int permission = mContext.checkCallingOrSelfPermission(
22190                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22191        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22192        enforceCrossUserPermission(callingUid, userId,
22193                true /* requireFullPermission */, true /* checkShell */, "stop package");
22194        // writer
22195        synchronized (mPackages) {
22196            final PackageSetting ps = mSettings.mPackages.get(packageName);
22197            if (!filterAppAccessLPr(ps, callingUid, userId)
22198                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22199                            allowedByPermission, callingUid, userId)) {
22200                scheduleWritePackageRestrictionsLocked(userId);
22201            }
22202        }
22203    }
22204
22205    @Override
22206    public String getInstallerPackageName(String packageName) {
22207        final int callingUid = Binder.getCallingUid();
22208        if (getInstantAppPackageName(callingUid) != null) {
22209            return null;
22210        }
22211        // reader
22212        synchronized (mPackages) {
22213            final PackageSetting ps = mSettings.mPackages.get(packageName);
22214            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22215                return null;
22216            }
22217            return mSettings.getInstallerPackageNameLPr(packageName);
22218        }
22219    }
22220
22221    public boolean isOrphaned(String packageName) {
22222        // reader
22223        synchronized (mPackages) {
22224            return mSettings.isOrphaned(packageName);
22225        }
22226    }
22227
22228    @Override
22229    public int getApplicationEnabledSetting(String packageName, int userId) {
22230        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22231        int callingUid = Binder.getCallingUid();
22232        enforceCrossUserPermission(callingUid, userId,
22233                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22234        // reader
22235        synchronized (mPackages) {
22236            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22237                return COMPONENT_ENABLED_STATE_DISABLED;
22238            }
22239            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22240        }
22241    }
22242
22243    @Override
22244    public int getComponentEnabledSetting(ComponentName component, int userId) {
22245        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22246        int callingUid = Binder.getCallingUid();
22247        enforceCrossUserPermission(callingUid, userId,
22248                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22249        synchronized (mPackages) {
22250            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22251                    component, TYPE_UNKNOWN, userId)) {
22252                return COMPONENT_ENABLED_STATE_DISABLED;
22253            }
22254            return mSettings.getComponentEnabledSettingLPr(component, userId);
22255        }
22256    }
22257
22258    @Override
22259    public void enterSafeMode() {
22260        enforceSystemOrRoot("Only the system can request entering safe mode");
22261
22262        if (!mSystemReady) {
22263            mSafeMode = true;
22264        }
22265    }
22266
22267    @Override
22268    public void systemReady() {
22269        enforceSystemOrRoot("Only the system can claim the system is ready");
22270
22271        mSystemReady = true;
22272        final ContentResolver resolver = mContext.getContentResolver();
22273        ContentObserver co = new ContentObserver(mHandler) {
22274            @Override
22275            public void onChange(boolean selfChange) {
22276                mEphemeralAppsDisabled =
22277                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22278                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22279            }
22280        };
22281        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22282                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22283                false, co, UserHandle.USER_SYSTEM);
22284        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22285                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22286        co.onChange(true);
22287
22288        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22289        // disabled after already being started.
22290        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22291                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22292
22293        // Read the compatibilty setting when the system is ready.
22294        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22295                mContext.getContentResolver(),
22296                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22297        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22298        if (DEBUG_SETTINGS) {
22299            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22300        }
22301
22302        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22303
22304        synchronized (mPackages) {
22305            // Verify that all of the preferred activity components actually
22306            // exist.  It is possible for applications to be updated and at
22307            // that point remove a previously declared activity component that
22308            // had been set as a preferred activity.  We try to clean this up
22309            // the next time we encounter that preferred activity, but it is
22310            // possible for the user flow to never be able to return to that
22311            // situation so here we do a sanity check to make sure we haven't
22312            // left any junk around.
22313            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22314            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22315                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22316                removed.clear();
22317                for (PreferredActivity pa : pir.filterSet()) {
22318                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22319                        removed.add(pa);
22320                    }
22321                }
22322                if (removed.size() > 0) {
22323                    for (int r=0; r<removed.size(); r++) {
22324                        PreferredActivity pa = removed.get(r);
22325                        Slog.w(TAG, "Removing dangling preferred activity: "
22326                                + pa.mPref.mComponent);
22327                        pir.removeFilter(pa);
22328                    }
22329                    mSettings.writePackageRestrictionsLPr(
22330                            mSettings.mPreferredActivities.keyAt(i));
22331                }
22332            }
22333
22334            for (int userId : UserManagerService.getInstance().getUserIds()) {
22335                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22336                    grantPermissionsUserIds = ArrayUtils.appendInt(
22337                            grantPermissionsUserIds, userId);
22338                }
22339            }
22340        }
22341        sUserManager.systemReady();
22342
22343        // If we upgraded grant all default permissions before kicking off.
22344        for (int userId : grantPermissionsUserIds) {
22345            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22346        }
22347
22348        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22349            // If we did not grant default permissions, we preload from this the
22350            // default permission exceptions lazily to ensure we don't hit the
22351            // disk on a new user creation.
22352            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22353        }
22354
22355        // Now that we've scanned all packages, and granted any default
22356        // permissions, ensure permissions are updated. Beware of dragons if you
22357        // try optimizing this.
22358        synchronized (mPackages) {
22359            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
22360                    UPDATE_PERMISSIONS_ALL);
22361        }
22362
22363        // Kick off any messages waiting for system ready
22364        if (mPostSystemReadyMessages != null) {
22365            for (Message msg : mPostSystemReadyMessages) {
22366                msg.sendToTarget();
22367            }
22368            mPostSystemReadyMessages = null;
22369        }
22370
22371        // Watch for external volumes that come and go over time
22372        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22373        storage.registerListener(mStorageListener);
22374
22375        mInstallerService.systemReady();
22376        mPackageDexOptimizer.systemReady();
22377
22378        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22379                StorageManagerInternal.class);
22380        StorageManagerInternal.addExternalStoragePolicy(
22381                new StorageManagerInternal.ExternalStorageMountPolicy() {
22382            @Override
22383            public int getMountMode(int uid, String packageName) {
22384                if (Process.isIsolated(uid)) {
22385                    return Zygote.MOUNT_EXTERNAL_NONE;
22386                }
22387                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22388                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22389                }
22390                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22391                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22392                }
22393                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22394                    return Zygote.MOUNT_EXTERNAL_READ;
22395                }
22396                return Zygote.MOUNT_EXTERNAL_WRITE;
22397            }
22398
22399            @Override
22400            public boolean hasExternalStorage(int uid, String packageName) {
22401                return true;
22402            }
22403        });
22404
22405        // Now that we're mostly running, clean up stale users and apps
22406        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22407        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22408
22409        if (mPrivappPermissionsViolations != null) {
22410            Slog.wtf(TAG,"Signature|privileged permissions not in "
22411                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22412            mPrivappPermissionsViolations = null;
22413        }
22414    }
22415
22416    public void waitForAppDataPrepared() {
22417        if (mPrepareAppDataFuture == null) {
22418            return;
22419        }
22420        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22421        mPrepareAppDataFuture = null;
22422    }
22423
22424    @Override
22425    public boolean isSafeMode() {
22426        // allow instant applications
22427        return mSafeMode;
22428    }
22429
22430    @Override
22431    public boolean hasSystemUidErrors() {
22432        // allow instant applications
22433        return mHasSystemUidErrors;
22434    }
22435
22436    static String arrayToString(int[] array) {
22437        StringBuffer buf = new StringBuffer(128);
22438        buf.append('[');
22439        if (array != null) {
22440            for (int i=0; i<array.length; i++) {
22441                if (i > 0) buf.append(", ");
22442                buf.append(array[i]);
22443            }
22444        }
22445        buf.append(']');
22446        return buf.toString();
22447    }
22448
22449    static class DumpState {
22450        public static final int DUMP_LIBS = 1 << 0;
22451        public static final int DUMP_FEATURES = 1 << 1;
22452        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22453        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22454        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22455        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22456        public static final int DUMP_PERMISSIONS = 1 << 6;
22457        public static final int DUMP_PACKAGES = 1 << 7;
22458        public static final int DUMP_SHARED_USERS = 1 << 8;
22459        public static final int DUMP_MESSAGES = 1 << 9;
22460        public static final int DUMP_PROVIDERS = 1 << 10;
22461        public static final int DUMP_VERIFIERS = 1 << 11;
22462        public static final int DUMP_PREFERRED = 1 << 12;
22463        public static final int DUMP_PREFERRED_XML = 1 << 13;
22464        public static final int DUMP_KEYSETS = 1 << 14;
22465        public static final int DUMP_VERSION = 1 << 15;
22466        public static final int DUMP_INSTALLS = 1 << 16;
22467        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22468        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22469        public static final int DUMP_FROZEN = 1 << 19;
22470        public static final int DUMP_DEXOPT = 1 << 20;
22471        public static final int DUMP_COMPILER_STATS = 1 << 21;
22472        public static final int DUMP_CHANGES = 1 << 22;
22473        public static final int DUMP_VOLUMES = 1 << 23;
22474
22475        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22476
22477        private int mTypes;
22478
22479        private int mOptions;
22480
22481        private boolean mTitlePrinted;
22482
22483        private SharedUserSetting mSharedUser;
22484
22485        public boolean isDumping(int type) {
22486            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22487                return true;
22488            }
22489
22490            return (mTypes & type) != 0;
22491        }
22492
22493        public void setDump(int type) {
22494            mTypes |= type;
22495        }
22496
22497        public boolean isOptionEnabled(int option) {
22498            return (mOptions & option) != 0;
22499        }
22500
22501        public void setOptionEnabled(int option) {
22502            mOptions |= option;
22503        }
22504
22505        public boolean onTitlePrinted() {
22506            final boolean printed = mTitlePrinted;
22507            mTitlePrinted = true;
22508            return printed;
22509        }
22510
22511        public boolean getTitlePrinted() {
22512            return mTitlePrinted;
22513        }
22514
22515        public void setTitlePrinted(boolean enabled) {
22516            mTitlePrinted = enabled;
22517        }
22518
22519        public SharedUserSetting getSharedUser() {
22520            return mSharedUser;
22521        }
22522
22523        public void setSharedUser(SharedUserSetting user) {
22524            mSharedUser = user;
22525        }
22526    }
22527
22528    @Override
22529    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22530            FileDescriptor err, String[] args, ShellCallback callback,
22531            ResultReceiver resultReceiver) {
22532        (new PackageManagerShellCommand(this)).exec(
22533                this, in, out, err, args, callback, resultReceiver);
22534    }
22535
22536    @Override
22537    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22538        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22539
22540        DumpState dumpState = new DumpState();
22541        boolean fullPreferred = false;
22542        boolean checkin = false;
22543
22544        String packageName = null;
22545        ArraySet<String> permissionNames = null;
22546
22547        int opti = 0;
22548        while (opti < args.length) {
22549            String opt = args[opti];
22550            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22551                break;
22552            }
22553            opti++;
22554
22555            if ("-a".equals(opt)) {
22556                // Right now we only know how to print all.
22557            } else if ("-h".equals(opt)) {
22558                pw.println("Package manager dump options:");
22559                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22560                pw.println("    --checkin: dump for a checkin");
22561                pw.println("    -f: print details of intent filters");
22562                pw.println("    -h: print this help");
22563                pw.println("  cmd may be one of:");
22564                pw.println("    l[ibraries]: list known shared libraries");
22565                pw.println("    f[eatures]: list device features");
22566                pw.println("    k[eysets]: print known keysets");
22567                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22568                pw.println("    perm[issions]: dump permissions");
22569                pw.println("    permission [name ...]: dump declaration and use of given permission");
22570                pw.println("    pref[erred]: print preferred package settings");
22571                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22572                pw.println("    prov[iders]: dump content providers");
22573                pw.println("    p[ackages]: dump installed packages");
22574                pw.println("    s[hared-users]: dump shared user IDs");
22575                pw.println("    m[essages]: print collected runtime messages");
22576                pw.println("    v[erifiers]: print package verifier info");
22577                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22578                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22579                pw.println("    version: print database version info");
22580                pw.println("    write: write current settings now");
22581                pw.println("    installs: details about install sessions");
22582                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22583                pw.println("    dexopt: dump dexopt state");
22584                pw.println("    compiler-stats: dump compiler statistics");
22585                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22586                pw.println("    <package.name>: info about given package");
22587                return;
22588            } else if ("--checkin".equals(opt)) {
22589                checkin = true;
22590            } else if ("-f".equals(opt)) {
22591                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22592            } else if ("--proto".equals(opt)) {
22593                dumpProto(fd);
22594                return;
22595            } else {
22596                pw.println("Unknown argument: " + opt + "; use -h for help");
22597            }
22598        }
22599
22600        // Is the caller requesting to dump a particular piece of data?
22601        if (opti < args.length) {
22602            String cmd = args[opti];
22603            opti++;
22604            // Is this a package name?
22605            if ("android".equals(cmd) || cmd.contains(".")) {
22606                packageName = cmd;
22607                // When dumping a single package, we always dump all of its
22608                // filter information since the amount of data will be reasonable.
22609                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22610            } else if ("check-permission".equals(cmd)) {
22611                if (opti >= args.length) {
22612                    pw.println("Error: check-permission missing permission argument");
22613                    return;
22614                }
22615                String perm = args[opti];
22616                opti++;
22617                if (opti >= args.length) {
22618                    pw.println("Error: check-permission missing package argument");
22619                    return;
22620                }
22621
22622                String pkg = args[opti];
22623                opti++;
22624                int user = UserHandle.getUserId(Binder.getCallingUid());
22625                if (opti < args.length) {
22626                    try {
22627                        user = Integer.parseInt(args[opti]);
22628                    } catch (NumberFormatException e) {
22629                        pw.println("Error: check-permission user argument is not a number: "
22630                                + args[opti]);
22631                        return;
22632                    }
22633                }
22634
22635                // Normalize package name to handle renamed packages and static libs
22636                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22637
22638                pw.println(checkPermission(perm, pkg, user));
22639                return;
22640            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22641                dumpState.setDump(DumpState.DUMP_LIBS);
22642            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22643                dumpState.setDump(DumpState.DUMP_FEATURES);
22644            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22645                if (opti >= args.length) {
22646                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22647                            | DumpState.DUMP_SERVICE_RESOLVERS
22648                            | DumpState.DUMP_RECEIVER_RESOLVERS
22649                            | DumpState.DUMP_CONTENT_RESOLVERS);
22650                } else {
22651                    while (opti < args.length) {
22652                        String name = args[opti];
22653                        if ("a".equals(name) || "activity".equals(name)) {
22654                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22655                        } else if ("s".equals(name) || "service".equals(name)) {
22656                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22657                        } else if ("r".equals(name) || "receiver".equals(name)) {
22658                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22659                        } else if ("c".equals(name) || "content".equals(name)) {
22660                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22661                        } else {
22662                            pw.println("Error: unknown resolver table type: " + name);
22663                            return;
22664                        }
22665                        opti++;
22666                    }
22667                }
22668            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22669                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22670            } else if ("permission".equals(cmd)) {
22671                if (opti >= args.length) {
22672                    pw.println("Error: permission requires permission name");
22673                    return;
22674                }
22675                permissionNames = new ArraySet<>();
22676                while (opti < args.length) {
22677                    permissionNames.add(args[opti]);
22678                    opti++;
22679                }
22680                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22681                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22682            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22683                dumpState.setDump(DumpState.DUMP_PREFERRED);
22684            } else if ("preferred-xml".equals(cmd)) {
22685                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22686                if (opti < args.length && "--full".equals(args[opti])) {
22687                    fullPreferred = true;
22688                    opti++;
22689                }
22690            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22691                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22692            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22693                dumpState.setDump(DumpState.DUMP_PACKAGES);
22694            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22695                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22696            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22697                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22698            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22699                dumpState.setDump(DumpState.DUMP_MESSAGES);
22700            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22701                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22702            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22703                    || "intent-filter-verifiers".equals(cmd)) {
22704                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22705            } else if ("version".equals(cmd)) {
22706                dumpState.setDump(DumpState.DUMP_VERSION);
22707            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22708                dumpState.setDump(DumpState.DUMP_KEYSETS);
22709            } else if ("installs".equals(cmd)) {
22710                dumpState.setDump(DumpState.DUMP_INSTALLS);
22711            } else if ("frozen".equals(cmd)) {
22712                dumpState.setDump(DumpState.DUMP_FROZEN);
22713            } else if ("volumes".equals(cmd)) {
22714                dumpState.setDump(DumpState.DUMP_VOLUMES);
22715            } else if ("dexopt".equals(cmd)) {
22716                dumpState.setDump(DumpState.DUMP_DEXOPT);
22717            } else if ("compiler-stats".equals(cmd)) {
22718                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22719            } else if ("changes".equals(cmd)) {
22720                dumpState.setDump(DumpState.DUMP_CHANGES);
22721            } else if ("write".equals(cmd)) {
22722                synchronized (mPackages) {
22723                    mSettings.writeLPr();
22724                    pw.println("Settings written.");
22725                    return;
22726                }
22727            }
22728        }
22729
22730        if (checkin) {
22731            pw.println("vers,1");
22732        }
22733
22734        // reader
22735        synchronized (mPackages) {
22736            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22737                if (!checkin) {
22738                    if (dumpState.onTitlePrinted())
22739                        pw.println();
22740                    pw.println("Database versions:");
22741                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22742                }
22743            }
22744
22745            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22746                if (!checkin) {
22747                    if (dumpState.onTitlePrinted())
22748                        pw.println();
22749                    pw.println("Verifiers:");
22750                    pw.print("  Required: ");
22751                    pw.print(mRequiredVerifierPackage);
22752                    pw.print(" (uid=");
22753                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22754                            UserHandle.USER_SYSTEM));
22755                    pw.println(")");
22756                } else if (mRequiredVerifierPackage != null) {
22757                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22758                    pw.print(",");
22759                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22760                            UserHandle.USER_SYSTEM));
22761                }
22762            }
22763
22764            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22765                    packageName == null) {
22766                if (mIntentFilterVerifierComponent != null) {
22767                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22768                    if (!checkin) {
22769                        if (dumpState.onTitlePrinted())
22770                            pw.println();
22771                        pw.println("Intent Filter Verifier:");
22772                        pw.print("  Using: ");
22773                        pw.print(verifierPackageName);
22774                        pw.print(" (uid=");
22775                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22776                                UserHandle.USER_SYSTEM));
22777                        pw.println(")");
22778                    } else if (verifierPackageName != null) {
22779                        pw.print("ifv,"); pw.print(verifierPackageName);
22780                        pw.print(",");
22781                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22782                                UserHandle.USER_SYSTEM));
22783                    }
22784                } else {
22785                    pw.println();
22786                    pw.println("No Intent Filter Verifier available!");
22787                }
22788            }
22789
22790            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22791                boolean printedHeader = false;
22792                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22793                while (it.hasNext()) {
22794                    String libName = it.next();
22795                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22796                    if (versionedLib == null) {
22797                        continue;
22798                    }
22799                    final int versionCount = versionedLib.size();
22800                    for (int i = 0; i < versionCount; i++) {
22801                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22802                        if (!checkin) {
22803                            if (!printedHeader) {
22804                                if (dumpState.onTitlePrinted())
22805                                    pw.println();
22806                                pw.println("Libraries:");
22807                                printedHeader = true;
22808                            }
22809                            pw.print("  ");
22810                        } else {
22811                            pw.print("lib,");
22812                        }
22813                        pw.print(libEntry.info.getName());
22814                        if (libEntry.info.isStatic()) {
22815                            pw.print(" version=" + libEntry.info.getVersion());
22816                        }
22817                        if (!checkin) {
22818                            pw.print(" -> ");
22819                        }
22820                        if (libEntry.path != null) {
22821                            pw.print(" (jar) ");
22822                            pw.print(libEntry.path);
22823                        } else {
22824                            pw.print(" (apk) ");
22825                            pw.print(libEntry.apk);
22826                        }
22827                        pw.println();
22828                    }
22829                }
22830            }
22831
22832            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22833                if (dumpState.onTitlePrinted())
22834                    pw.println();
22835                if (!checkin) {
22836                    pw.println("Features:");
22837                }
22838
22839                synchronized (mAvailableFeatures) {
22840                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22841                        if (checkin) {
22842                            pw.print("feat,");
22843                            pw.print(feat.name);
22844                            pw.print(",");
22845                            pw.println(feat.version);
22846                        } else {
22847                            pw.print("  ");
22848                            pw.print(feat.name);
22849                            if (feat.version > 0) {
22850                                pw.print(" version=");
22851                                pw.print(feat.version);
22852                            }
22853                            pw.println();
22854                        }
22855                    }
22856                }
22857            }
22858
22859            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22860                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22861                        : "Activity Resolver Table:", "  ", packageName,
22862                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22863                    dumpState.setTitlePrinted(true);
22864                }
22865            }
22866            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22867                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22868                        : "Receiver Resolver Table:", "  ", packageName,
22869                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22870                    dumpState.setTitlePrinted(true);
22871                }
22872            }
22873            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22874                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22875                        : "Service Resolver Table:", "  ", packageName,
22876                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22877                    dumpState.setTitlePrinted(true);
22878                }
22879            }
22880            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22881                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22882                        : "Provider Resolver Table:", "  ", packageName,
22883                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22884                    dumpState.setTitlePrinted(true);
22885                }
22886            }
22887
22888            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22889                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22890                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22891                    int user = mSettings.mPreferredActivities.keyAt(i);
22892                    if (pir.dump(pw,
22893                            dumpState.getTitlePrinted()
22894                                ? "\nPreferred Activities User " + user + ":"
22895                                : "Preferred Activities User " + user + ":", "  ",
22896                            packageName, true, false)) {
22897                        dumpState.setTitlePrinted(true);
22898                    }
22899                }
22900            }
22901
22902            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22903                pw.flush();
22904                FileOutputStream fout = new FileOutputStream(fd);
22905                BufferedOutputStream str = new BufferedOutputStream(fout);
22906                XmlSerializer serializer = new FastXmlSerializer();
22907                try {
22908                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22909                    serializer.startDocument(null, true);
22910                    serializer.setFeature(
22911                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22912                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22913                    serializer.endDocument();
22914                    serializer.flush();
22915                } catch (IllegalArgumentException e) {
22916                    pw.println("Failed writing: " + e);
22917                } catch (IllegalStateException e) {
22918                    pw.println("Failed writing: " + e);
22919                } catch (IOException e) {
22920                    pw.println("Failed writing: " + e);
22921                }
22922            }
22923
22924            if (!checkin
22925                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22926                    && packageName == null) {
22927                pw.println();
22928                int count = mSettings.mPackages.size();
22929                if (count == 0) {
22930                    pw.println("No applications!");
22931                    pw.println();
22932                } else {
22933                    final String prefix = "  ";
22934                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22935                    if (allPackageSettings.size() == 0) {
22936                        pw.println("No domain preferred apps!");
22937                        pw.println();
22938                    } else {
22939                        pw.println("App verification status:");
22940                        pw.println();
22941                        count = 0;
22942                        for (PackageSetting ps : allPackageSettings) {
22943                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22944                            if (ivi == null || ivi.getPackageName() == null) continue;
22945                            pw.println(prefix + "Package: " + ivi.getPackageName());
22946                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22947                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22948                            pw.println();
22949                            count++;
22950                        }
22951                        if (count == 0) {
22952                            pw.println(prefix + "No app verification established.");
22953                            pw.println();
22954                        }
22955                        for (int userId : sUserManager.getUserIds()) {
22956                            pw.println("App linkages for user " + userId + ":");
22957                            pw.println();
22958                            count = 0;
22959                            for (PackageSetting ps : allPackageSettings) {
22960                                final long status = ps.getDomainVerificationStatusForUser(userId);
22961                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22962                                        && !DEBUG_DOMAIN_VERIFICATION) {
22963                                    continue;
22964                                }
22965                                pw.println(prefix + "Package: " + ps.name);
22966                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22967                                String statusStr = IntentFilterVerificationInfo.
22968                                        getStatusStringFromValue(status);
22969                                pw.println(prefix + "Status:  " + statusStr);
22970                                pw.println();
22971                                count++;
22972                            }
22973                            if (count == 0) {
22974                                pw.println(prefix + "No configured app linkages.");
22975                                pw.println();
22976                            }
22977                        }
22978                    }
22979                }
22980            }
22981
22982            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22983                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22984                if (packageName == null && permissionNames == null) {
22985                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22986                        if (iperm == 0) {
22987                            if (dumpState.onTitlePrinted())
22988                                pw.println();
22989                            pw.println("AppOp Permissions:");
22990                        }
22991                        pw.print("  AppOp Permission ");
22992                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22993                        pw.println(":");
22994                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22995                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22996                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22997                        }
22998                    }
22999                }
23000            }
23001
23002            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
23003                boolean printedSomething = false;
23004                for (PackageParser.Provider p : mProviders.mProviders.values()) {
23005                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23006                        continue;
23007                    }
23008                    if (!printedSomething) {
23009                        if (dumpState.onTitlePrinted())
23010                            pw.println();
23011                        pw.println("Registered ContentProviders:");
23012                        printedSomething = true;
23013                    }
23014                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
23015                    pw.print("    "); pw.println(p.toString());
23016                }
23017                printedSomething = false;
23018                for (Map.Entry<String, PackageParser.Provider> entry :
23019                        mProvidersByAuthority.entrySet()) {
23020                    PackageParser.Provider p = entry.getValue();
23021                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23022                        continue;
23023                    }
23024                    if (!printedSomething) {
23025                        if (dumpState.onTitlePrinted())
23026                            pw.println();
23027                        pw.println("ContentProvider Authorities:");
23028                        printedSomething = true;
23029                    }
23030                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
23031                    pw.print("    "); pw.println(p.toString());
23032                    if (p.info != null && p.info.applicationInfo != null) {
23033                        final String appInfo = p.info.applicationInfo.toString();
23034                        pw.print("      applicationInfo="); pw.println(appInfo);
23035                    }
23036                }
23037            }
23038
23039            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
23040                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
23041            }
23042
23043            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
23044                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
23045            }
23046
23047            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
23048                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
23049            }
23050
23051            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
23052                if (dumpState.onTitlePrinted()) pw.println();
23053                pw.println("Package Changes:");
23054                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
23055                final int K = mChangedPackages.size();
23056                for (int i = 0; i < K; i++) {
23057                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
23058                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
23059                    final int N = changes.size();
23060                    if (N == 0) {
23061                        pw.print("    "); pw.println("No packages changed");
23062                    } else {
23063                        for (int j = 0; j < N; j++) {
23064                            final String pkgName = changes.valueAt(j);
23065                            final int sequenceNumber = changes.keyAt(j);
23066                            pw.print("    ");
23067                            pw.print("seq=");
23068                            pw.print(sequenceNumber);
23069                            pw.print(", package=");
23070                            pw.println(pkgName);
23071                        }
23072                    }
23073                }
23074            }
23075
23076            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23077                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23078            }
23079
23080            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23081                // XXX should handle packageName != null by dumping only install data that
23082                // the given package is involved with.
23083                if (dumpState.onTitlePrinted()) pw.println();
23084
23085                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23086                ipw.println();
23087                ipw.println("Frozen packages:");
23088                ipw.increaseIndent();
23089                if (mFrozenPackages.size() == 0) {
23090                    ipw.println("(none)");
23091                } else {
23092                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23093                        ipw.println(mFrozenPackages.valueAt(i));
23094                    }
23095                }
23096                ipw.decreaseIndent();
23097            }
23098
23099            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23100                if (dumpState.onTitlePrinted()) pw.println();
23101
23102                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23103                ipw.println();
23104                ipw.println("Loaded volumes:");
23105                ipw.increaseIndent();
23106                if (mLoadedVolumes.size() == 0) {
23107                    ipw.println("(none)");
23108                } else {
23109                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23110                        ipw.println(mLoadedVolumes.valueAt(i));
23111                    }
23112                }
23113                ipw.decreaseIndent();
23114            }
23115
23116            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23117                if (dumpState.onTitlePrinted()) pw.println();
23118                dumpDexoptStateLPr(pw, packageName);
23119            }
23120
23121            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23122                if (dumpState.onTitlePrinted()) pw.println();
23123                dumpCompilerStatsLPr(pw, packageName);
23124            }
23125
23126            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23127                if (dumpState.onTitlePrinted()) pw.println();
23128                mSettings.dumpReadMessagesLPr(pw, dumpState);
23129
23130                pw.println();
23131                pw.println("Package warning messages:");
23132                BufferedReader in = null;
23133                String line = null;
23134                try {
23135                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23136                    while ((line = in.readLine()) != null) {
23137                        if (line.contains("ignored: updated version")) continue;
23138                        pw.println(line);
23139                    }
23140                } catch (IOException ignored) {
23141                } finally {
23142                    IoUtils.closeQuietly(in);
23143                }
23144            }
23145
23146            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23147                BufferedReader in = null;
23148                String line = null;
23149                try {
23150                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23151                    while ((line = in.readLine()) != null) {
23152                        if (line.contains("ignored: updated version")) continue;
23153                        pw.print("msg,");
23154                        pw.println(line);
23155                    }
23156                } catch (IOException ignored) {
23157                } finally {
23158                    IoUtils.closeQuietly(in);
23159                }
23160            }
23161        }
23162
23163        // PackageInstaller should be called outside of mPackages lock
23164        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23165            // XXX should handle packageName != null by dumping only install data that
23166            // the given package is involved with.
23167            if (dumpState.onTitlePrinted()) pw.println();
23168            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23169        }
23170    }
23171
23172    private void dumpProto(FileDescriptor fd) {
23173        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23174
23175        synchronized (mPackages) {
23176            final long requiredVerifierPackageToken =
23177                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23178            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23179            proto.write(
23180                    PackageServiceDumpProto.PackageShortProto.UID,
23181                    getPackageUid(
23182                            mRequiredVerifierPackage,
23183                            MATCH_DEBUG_TRIAGED_MISSING,
23184                            UserHandle.USER_SYSTEM));
23185            proto.end(requiredVerifierPackageToken);
23186
23187            if (mIntentFilterVerifierComponent != null) {
23188                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23189                final long verifierPackageToken =
23190                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23191                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23192                proto.write(
23193                        PackageServiceDumpProto.PackageShortProto.UID,
23194                        getPackageUid(
23195                                verifierPackageName,
23196                                MATCH_DEBUG_TRIAGED_MISSING,
23197                                UserHandle.USER_SYSTEM));
23198                proto.end(verifierPackageToken);
23199            }
23200
23201            dumpSharedLibrariesProto(proto);
23202            dumpFeaturesProto(proto);
23203            mSettings.dumpPackagesProto(proto);
23204            mSettings.dumpSharedUsersProto(proto);
23205            dumpMessagesProto(proto);
23206        }
23207        proto.flush();
23208    }
23209
23210    private void dumpMessagesProto(ProtoOutputStream proto) {
23211        BufferedReader in = null;
23212        String line = null;
23213        try {
23214            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23215            while ((line = in.readLine()) != null) {
23216                if (line.contains("ignored: updated version")) continue;
23217                proto.write(PackageServiceDumpProto.MESSAGES, line);
23218            }
23219        } catch (IOException ignored) {
23220        } finally {
23221            IoUtils.closeQuietly(in);
23222        }
23223    }
23224
23225    private void dumpFeaturesProto(ProtoOutputStream proto) {
23226        synchronized (mAvailableFeatures) {
23227            final int count = mAvailableFeatures.size();
23228            for (int i = 0; i < count; i++) {
23229                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23230                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23231                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23232                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23233                proto.end(featureToken);
23234            }
23235        }
23236    }
23237
23238    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23239        final int count = mSharedLibraries.size();
23240        for (int i = 0; i < count; i++) {
23241            final String libName = mSharedLibraries.keyAt(i);
23242            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23243            if (versionedLib == null) {
23244                continue;
23245            }
23246            final int versionCount = versionedLib.size();
23247            for (int j = 0; j < versionCount; j++) {
23248                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23249                final long sharedLibraryToken =
23250                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23251                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23252                final boolean isJar = (libEntry.path != null);
23253                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23254                if (isJar) {
23255                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23256                } else {
23257                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23258                }
23259                proto.end(sharedLibraryToken);
23260            }
23261        }
23262    }
23263
23264    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23265        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23266        ipw.println();
23267        ipw.println("Dexopt state:");
23268        ipw.increaseIndent();
23269        Collection<PackageParser.Package> packages = null;
23270        if (packageName != null) {
23271            PackageParser.Package targetPackage = mPackages.get(packageName);
23272            if (targetPackage != null) {
23273                packages = Collections.singletonList(targetPackage);
23274            } else {
23275                ipw.println("Unable to find package: " + packageName);
23276                return;
23277            }
23278        } else {
23279            packages = mPackages.values();
23280        }
23281
23282        for (PackageParser.Package pkg : packages) {
23283            ipw.println("[" + pkg.packageName + "]");
23284            ipw.increaseIndent();
23285            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23286                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23287            ipw.decreaseIndent();
23288        }
23289    }
23290
23291    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23292        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23293        ipw.println();
23294        ipw.println("Compiler stats:");
23295        ipw.increaseIndent();
23296        Collection<PackageParser.Package> packages = null;
23297        if (packageName != null) {
23298            PackageParser.Package targetPackage = mPackages.get(packageName);
23299            if (targetPackage != null) {
23300                packages = Collections.singletonList(targetPackage);
23301            } else {
23302                ipw.println("Unable to find package: " + packageName);
23303                return;
23304            }
23305        } else {
23306            packages = mPackages.values();
23307        }
23308
23309        for (PackageParser.Package pkg : packages) {
23310            ipw.println("[" + pkg.packageName + "]");
23311            ipw.increaseIndent();
23312
23313            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23314            if (stats == null) {
23315                ipw.println("(No recorded stats)");
23316            } else {
23317                stats.dump(ipw);
23318            }
23319            ipw.decreaseIndent();
23320        }
23321    }
23322
23323    private String dumpDomainString(String packageName) {
23324        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23325                .getList();
23326        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23327
23328        ArraySet<String> result = new ArraySet<>();
23329        if (iviList.size() > 0) {
23330            for (IntentFilterVerificationInfo ivi : iviList) {
23331                for (String host : ivi.getDomains()) {
23332                    result.add(host);
23333                }
23334            }
23335        }
23336        if (filters != null && filters.size() > 0) {
23337            for (IntentFilter filter : filters) {
23338                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23339                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23340                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23341                    result.addAll(filter.getHostsList());
23342                }
23343            }
23344        }
23345
23346        StringBuilder sb = new StringBuilder(result.size() * 16);
23347        for (String domain : result) {
23348            if (sb.length() > 0) sb.append(" ");
23349            sb.append(domain);
23350        }
23351        return sb.toString();
23352    }
23353
23354    // ------- apps on sdcard specific code -------
23355    static final boolean DEBUG_SD_INSTALL = false;
23356
23357    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23358
23359    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23360
23361    private boolean mMediaMounted = false;
23362
23363    static String getEncryptKey() {
23364        try {
23365            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23366                    SD_ENCRYPTION_KEYSTORE_NAME);
23367            if (sdEncKey == null) {
23368                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23369                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23370                if (sdEncKey == null) {
23371                    Slog.e(TAG, "Failed to create encryption keys");
23372                    return null;
23373                }
23374            }
23375            return sdEncKey;
23376        } catch (NoSuchAlgorithmException nsae) {
23377            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23378            return null;
23379        } catch (IOException ioe) {
23380            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23381            return null;
23382        }
23383    }
23384
23385    /*
23386     * Update media status on PackageManager.
23387     */
23388    @Override
23389    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23390        enforceSystemOrRoot("Media status can only be updated by the system");
23391        // reader; this apparently protects mMediaMounted, but should probably
23392        // be a different lock in that case.
23393        synchronized (mPackages) {
23394            Log.i(TAG, "Updating external media status from "
23395                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23396                    + (mediaStatus ? "mounted" : "unmounted"));
23397            if (DEBUG_SD_INSTALL)
23398                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23399                        + ", mMediaMounted=" + mMediaMounted);
23400            if (mediaStatus == mMediaMounted) {
23401                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23402                        : 0, -1);
23403                mHandler.sendMessage(msg);
23404                return;
23405            }
23406            mMediaMounted = mediaStatus;
23407        }
23408        // Queue up an async operation since the package installation may take a
23409        // little while.
23410        mHandler.post(new Runnable() {
23411            public void run() {
23412                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23413            }
23414        });
23415    }
23416
23417    /**
23418     * Called by StorageManagerService when the initial ASECs to scan are available.
23419     * Should block until all the ASEC containers are finished being scanned.
23420     */
23421    public void scanAvailableAsecs() {
23422        updateExternalMediaStatusInner(true, false, false);
23423    }
23424
23425    /*
23426     * Collect information of applications on external media, map them against
23427     * existing containers and update information based on current mount status.
23428     * Please note that we always have to report status if reportStatus has been
23429     * set to true especially when unloading packages.
23430     */
23431    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23432            boolean externalStorage) {
23433        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23434        int[] uidArr = EmptyArray.INT;
23435
23436        final String[] list = PackageHelper.getSecureContainerList();
23437        if (ArrayUtils.isEmpty(list)) {
23438            Log.i(TAG, "No secure containers found");
23439        } else {
23440            // Process list of secure containers and categorize them
23441            // as active or stale based on their package internal state.
23442
23443            // reader
23444            synchronized (mPackages) {
23445                for (String cid : list) {
23446                    // Leave stages untouched for now; installer service owns them
23447                    if (PackageInstallerService.isStageName(cid)) continue;
23448
23449                    if (DEBUG_SD_INSTALL)
23450                        Log.i(TAG, "Processing container " + cid);
23451                    String pkgName = getAsecPackageName(cid);
23452                    if (pkgName == null) {
23453                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23454                        continue;
23455                    }
23456                    if (DEBUG_SD_INSTALL)
23457                        Log.i(TAG, "Looking for pkg : " + pkgName);
23458
23459                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23460                    if (ps == null) {
23461                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23462                        continue;
23463                    }
23464
23465                    /*
23466                     * Skip packages that are not external if we're unmounting
23467                     * external storage.
23468                     */
23469                    if (externalStorage && !isMounted && !isExternal(ps)) {
23470                        continue;
23471                    }
23472
23473                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23474                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23475                    // The package status is changed only if the code path
23476                    // matches between settings and the container id.
23477                    if (ps.codePathString != null
23478                            && ps.codePathString.startsWith(args.getCodePath())) {
23479                        if (DEBUG_SD_INSTALL) {
23480                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23481                                    + " at code path: " + ps.codePathString);
23482                        }
23483
23484                        // We do have a valid package installed on sdcard
23485                        processCids.put(args, ps.codePathString);
23486                        final int uid = ps.appId;
23487                        if (uid != -1) {
23488                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23489                        }
23490                    } else {
23491                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23492                                + ps.codePathString);
23493                    }
23494                }
23495            }
23496
23497            Arrays.sort(uidArr);
23498        }
23499
23500        // Process packages with valid entries.
23501        if (isMounted) {
23502            if (DEBUG_SD_INSTALL)
23503                Log.i(TAG, "Loading packages");
23504            loadMediaPackages(processCids, uidArr, externalStorage);
23505            startCleaningPackages();
23506            mInstallerService.onSecureContainersAvailable();
23507        } else {
23508            if (DEBUG_SD_INSTALL)
23509                Log.i(TAG, "Unloading packages");
23510            unloadMediaPackages(processCids, uidArr, reportStatus);
23511        }
23512    }
23513
23514    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23515            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23516        final int size = infos.size();
23517        final String[] packageNames = new String[size];
23518        final int[] packageUids = new int[size];
23519        for (int i = 0; i < size; i++) {
23520            final ApplicationInfo info = infos.get(i);
23521            packageNames[i] = info.packageName;
23522            packageUids[i] = info.uid;
23523        }
23524        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23525                finishedReceiver);
23526    }
23527
23528    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23529            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23530        sendResourcesChangedBroadcast(mediaStatus, replacing,
23531                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23532    }
23533
23534    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23535            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23536        int size = pkgList.length;
23537        if (size > 0) {
23538            // Send broadcasts here
23539            Bundle extras = new Bundle();
23540            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23541            if (uidArr != null) {
23542                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23543            }
23544            if (replacing) {
23545                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23546            }
23547            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23548                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23549            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23550        }
23551    }
23552
23553   /*
23554     * Look at potentially valid container ids from processCids If package
23555     * information doesn't match the one on record or package scanning fails,
23556     * the cid is added to list of removeCids. We currently don't delete stale
23557     * containers.
23558     */
23559    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23560            boolean externalStorage) {
23561        ArrayList<String> pkgList = new ArrayList<String>();
23562        Set<AsecInstallArgs> keys = processCids.keySet();
23563
23564        for (AsecInstallArgs args : keys) {
23565            String codePath = processCids.get(args);
23566            if (DEBUG_SD_INSTALL)
23567                Log.i(TAG, "Loading container : " + args.cid);
23568            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23569            try {
23570                // Make sure there are no container errors first.
23571                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23572                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23573                            + " when installing from sdcard");
23574                    continue;
23575                }
23576                // Check code path here.
23577                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23578                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23579                            + " does not match one in settings " + codePath);
23580                    continue;
23581                }
23582                // Parse package
23583                int parseFlags = mDefParseFlags;
23584                if (args.isExternalAsec()) {
23585                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23586                }
23587                if (args.isFwdLocked()) {
23588                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23589                }
23590
23591                synchronized (mInstallLock) {
23592                    PackageParser.Package pkg = null;
23593                    try {
23594                        // Sadly we don't know the package name yet to freeze it
23595                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23596                                SCAN_IGNORE_FROZEN, 0, null);
23597                    } catch (PackageManagerException e) {
23598                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23599                    }
23600                    // Scan the package
23601                    if (pkg != null) {
23602                        /*
23603                         * TODO why is the lock being held? doPostInstall is
23604                         * called in other places without the lock. This needs
23605                         * to be straightened out.
23606                         */
23607                        // writer
23608                        synchronized (mPackages) {
23609                            retCode = PackageManager.INSTALL_SUCCEEDED;
23610                            pkgList.add(pkg.packageName);
23611                            // Post process args
23612                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23613                                    pkg.applicationInfo.uid);
23614                        }
23615                    } else {
23616                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23617                    }
23618                }
23619
23620            } finally {
23621                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23622                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23623                }
23624            }
23625        }
23626        // writer
23627        synchronized (mPackages) {
23628            // If the platform SDK has changed since the last time we booted,
23629            // we need to re-grant app permission to catch any new ones that
23630            // appear. This is really a hack, and means that apps can in some
23631            // cases get permissions that the user didn't initially explicitly
23632            // allow... it would be nice to have some better way to handle
23633            // this situation.
23634            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23635                    : mSettings.getInternalVersion();
23636            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23637                    : StorageManager.UUID_PRIVATE_INTERNAL;
23638
23639            int updateFlags = UPDATE_PERMISSIONS_ALL;
23640            if (ver.sdkVersion != mSdkVersion) {
23641                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23642                        + mSdkVersion + "; regranting permissions for external");
23643                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23644            }
23645            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23646
23647            // Yay, everything is now upgraded
23648            ver.forceCurrent();
23649
23650            // can downgrade to reader
23651            // Persist settings
23652            mSettings.writeLPr();
23653        }
23654        // Send a broadcast to let everyone know we are done processing
23655        if (pkgList.size() > 0) {
23656            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23657        }
23658    }
23659
23660   /*
23661     * Utility method to unload a list of specified containers
23662     */
23663    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23664        // Just unmount all valid containers.
23665        for (AsecInstallArgs arg : cidArgs) {
23666            synchronized (mInstallLock) {
23667                arg.doPostDeleteLI(false);
23668           }
23669       }
23670   }
23671
23672    /*
23673     * Unload packages mounted on external media. This involves deleting package
23674     * data from internal structures, sending broadcasts about disabled packages,
23675     * gc'ing to free up references, unmounting all secure containers
23676     * corresponding to packages on external media, and posting a
23677     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23678     * that we always have to post this message if status has been requested no
23679     * matter what.
23680     */
23681    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23682            final boolean reportStatus) {
23683        if (DEBUG_SD_INSTALL)
23684            Log.i(TAG, "unloading media packages");
23685        ArrayList<String> pkgList = new ArrayList<String>();
23686        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23687        final Set<AsecInstallArgs> keys = processCids.keySet();
23688        for (AsecInstallArgs args : keys) {
23689            String pkgName = args.getPackageName();
23690            if (DEBUG_SD_INSTALL)
23691                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23692            // Delete package internally
23693            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23694            synchronized (mInstallLock) {
23695                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23696                final boolean res;
23697                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23698                        "unloadMediaPackages")) {
23699                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23700                            null);
23701                }
23702                if (res) {
23703                    pkgList.add(pkgName);
23704                } else {
23705                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23706                    failedList.add(args);
23707                }
23708            }
23709        }
23710
23711        // reader
23712        synchronized (mPackages) {
23713            // We didn't update the settings after removing each package;
23714            // write them now for all packages.
23715            mSettings.writeLPr();
23716        }
23717
23718        // We have to absolutely send UPDATED_MEDIA_STATUS only
23719        // after confirming that all the receivers processed the ordered
23720        // broadcast when packages get disabled, force a gc to clean things up.
23721        // and unload all the containers.
23722        if (pkgList.size() > 0) {
23723            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23724                    new IIntentReceiver.Stub() {
23725                public void performReceive(Intent intent, int resultCode, String data,
23726                        Bundle extras, boolean ordered, boolean sticky,
23727                        int sendingUser) throws RemoteException {
23728                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23729                            reportStatus ? 1 : 0, 1, keys);
23730                    mHandler.sendMessage(msg);
23731                }
23732            });
23733        } else {
23734            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23735                    keys);
23736            mHandler.sendMessage(msg);
23737        }
23738    }
23739
23740    private void loadPrivatePackages(final VolumeInfo vol) {
23741        mHandler.post(new Runnable() {
23742            @Override
23743            public void run() {
23744                loadPrivatePackagesInner(vol);
23745            }
23746        });
23747    }
23748
23749    private void loadPrivatePackagesInner(VolumeInfo vol) {
23750        final String volumeUuid = vol.fsUuid;
23751        if (TextUtils.isEmpty(volumeUuid)) {
23752            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23753            return;
23754        }
23755
23756        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23757        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23758        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23759
23760        final VersionInfo ver;
23761        final List<PackageSetting> packages;
23762        synchronized (mPackages) {
23763            ver = mSettings.findOrCreateVersion(volumeUuid);
23764            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23765        }
23766
23767        for (PackageSetting ps : packages) {
23768            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23769            synchronized (mInstallLock) {
23770                final PackageParser.Package pkg;
23771                try {
23772                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23773                    loaded.add(pkg.applicationInfo);
23774
23775                } catch (PackageManagerException e) {
23776                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23777                }
23778
23779                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23780                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23781                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23782                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23783                }
23784            }
23785        }
23786
23787        // Reconcile app data for all started/unlocked users
23788        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23789        final UserManager um = mContext.getSystemService(UserManager.class);
23790        UserManagerInternal umInternal = getUserManagerInternal();
23791        for (UserInfo user : um.getUsers()) {
23792            final int flags;
23793            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23794                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23795            } else if (umInternal.isUserRunning(user.id)) {
23796                flags = StorageManager.FLAG_STORAGE_DE;
23797            } else {
23798                continue;
23799            }
23800
23801            try {
23802                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23803                synchronized (mInstallLock) {
23804                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23805                }
23806            } catch (IllegalStateException e) {
23807                // Device was probably ejected, and we'll process that event momentarily
23808                Slog.w(TAG, "Failed to prepare storage: " + e);
23809            }
23810        }
23811
23812        synchronized (mPackages) {
23813            int updateFlags = UPDATE_PERMISSIONS_ALL;
23814            if (ver.sdkVersion != mSdkVersion) {
23815                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23816                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23817                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23818            }
23819            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23820
23821            // Yay, everything is now upgraded
23822            ver.forceCurrent();
23823
23824            mSettings.writeLPr();
23825        }
23826
23827        for (PackageFreezer freezer : freezers) {
23828            freezer.close();
23829        }
23830
23831        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23832        sendResourcesChangedBroadcast(true, false, loaded, null);
23833        mLoadedVolumes.add(vol.getId());
23834    }
23835
23836    private void unloadPrivatePackages(final VolumeInfo vol) {
23837        mHandler.post(new Runnable() {
23838            @Override
23839            public void run() {
23840                unloadPrivatePackagesInner(vol);
23841            }
23842        });
23843    }
23844
23845    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23846        final String volumeUuid = vol.fsUuid;
23847        if (TextUtils.isEmpty(volumeUuid)) {
23848            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23849            return;
23850        }
23851
23852        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23853        synchronized (mInstallLock) {
23854        synchronized (mPackages) {
23855            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23856            for (PackageSetting ps : packages) {
23857                if (ps.pkg == null) continue;
23858
23859                final ApplicationInfo info = ps.pkg.applicationInfo;
23860                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23861                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23862
23863                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23864                        "unloadPrivatePackagesInner")) {
23865                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23866                            false, null)) {
23867                        unloaded.add(info);
23868                    } else {
23869                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23870                    }
23871                }
23872
23873                // Try very hard to release any references to this package
23874                // so we don't risk the system server being killed due to
23875                // open FDs
23876                AttributeCache.instance().removePackage(ps.name);
23877            }
23878
23879            mSettings.writeLPr();
23880        }
23881        }
23882
23883        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23884        sendResourcesChangedBroadcast(false, false, unloaded, null);
23885        mLoadedVolumes.remove(vol.getId());
23886
23887        // Try very hard to release any references to this path so we don't risk
23888        // the system server being killed due to open FDs
23889        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23890
23891        for (int i = 0; i < 3; i++) {
23892            System.gc();
23893            System.runFinalization();
23894        }
23895    }
23896
23897    private void assertPackageKnown(String volumeUuid, String packageName)
23898            throws PackageManagerException {
23899        synchronized (mPackages) {
23900            // Normalize package name to handle renamed packages
23901            packageName = normalizePackageNameLPr(packageName);
23902
23903            final PackageSetting ps = mSettings.mPackages.get(packageName);
23904            if (ps == null) {
23905                throw new PackageManagerException("Package " + packageName + " is unknown");
23906            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23907                throw new PackageManagerException(
23908                        "Package " + packageName + " found on unknown volume " + volumeUuid
23909                                + "; expected volume " + ps.volumeUuid);
23910            }
23911        }
23912    }
23913
23914    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23915            throws PackageManagerException {
23916        synchronized (mPackages) {
23917            // Normalize package name to handle renamed packages
23918            packageName = normalizePackageNameLPr(packageName);
23919
23920            final PackageSetting ps = mSettings.mPackages.get(packageName);
23921            if (ps == null) {
23922                throw new PackageManagerException("Package " + packageName + " is unknown");
23923            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23924                throw new PackageManagerException(
23925                        "Package " + packageName + " found on unknown volume " + volumeUuid
23926                                + "; expected volume " + ps.volumeUuid);
23927            } else if (!ps.getInstalled(userId)) {
23928                throw new PackageManagerException(
23929                        "Package " + packageName + " not installed for user " + userId);
23930            }
23931        }
23932    }
23933
23934    private List<String> collectAbsoluteCodePaths() {
23935        synchronized (mPackages) {
23936            List<String> codePaths = new ArrayList<>();
23937            final int packageCount = mSettings.mPackages.size();
23938            for (int i = 0; i < packageCount; i++) {
23939                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23940                codePaths.add(ps.codePath.getAbsolutePath());
23941            }
23942            return codePaths;
23943        }
23944    }
23945
23946    /**
23947     * Examine all apps present on given mounted volume, and destroy apps that
23948     * aren't expected, either due to uninstallation or reinstallation on
23949     * another volume.
23950     */
23951    private void reconcileApps(String volumeUuid) {
23952        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23953        List<File> filesToDelete = null;
23954
23955        final File[] files = FileUtils.listFilesOrEmpty(
23956                Environment.getDataAppDirectory(volumeUuid));
23957        for (File file : files) {
23958            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23959                    && !PackageInstallerService.isStageName(file.getName());
23960            if (!isPackage) {
23961                // Ignore entries which are not packages
23962                continue;
23963            }
23964
23965            String absolutePath = file.getAbsolutePath();
23966
23967            boolean pathValid = false;
23968            final int absoluteCodePathCount = absoluteCodePaths.size();
23969            for (int i = 0; i < absoluteCodePathCount; i++) {
23970                String absoluteCodePath = absoluteCodePaths.get(i);
23971                if (absolutePath.startsWith(absoluteCodePath)) {
23972                    pathValid = true;
23973                    break;
23974                }
23975            }
23976
23977            if (!pathValid) {
23978                if (filesToDelete == null) {
23979                    filesToDelete = new ArrayList<>();
23980                }
23981                filesToDelete.add(file);
23982            }
23983        }
23984
23985        if (filesToDelete != null) {
23986            final int fileToDeleteCount = filesToDelete.size();
23987            for (int i = 0; i < fileToDeleteCount; i++) {
23988                File fileToDelete = filesToDelete.get(i);
23989                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23990                synchronized (mInstallLock) {
23991                    removeCodePathLI(fileToDelete);
23992                }
23993            }
23994        }
23995    }
23996
23997    /**
23998     * Reconcile all app data for the given user.
23999     * <p>
24000     * Verifies that directories exist and that ownership and labeling is
24001     * correct for all installed apps on all mounted volumes.
24002     */
24003    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
24004        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24005        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
24006            final String volumeUuid = vol.getFsUuid();
24007            synchronized (mInstallLock) {
24008                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
24009            }
24010        }
24011    }
24012
24013    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24014            boolean migrateAppData) {
24015        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
24016    }
24017
24018    /**
24019     * Reconcile all app data on given mounted volume.
24020     * <p>
24021     * Destroys app data that isn't expected, either due to uninstallation or
24022     * reinstallation on another volume.
24023     * <p>
24024     * Verifies that directories exist and that ownership and labeling is
24025     * correct for all installed apps.
24026     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
24027     */
24028    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24029            boolean migrateAppData, boolean onlyCoreApps) {
24030        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
24031                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
24032        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
24033
24034        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
24035        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
24036
24037        // First look for stale data that doesn't belong, and check if things
24038        // have changed since we did our last restorecon
24039        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24040            if (StorageManager.isFileEncryptedNativeOrEmulated()
24041                    && !StorageManager.isUserKeyUnlocked(userId)) {
24042                throw new RuntimeException(
24043                        "Yikes, someone asked us to reconcile CE storage while " + userId
24044                                + " was still locked; this would have caused massive data loss!");
24045            }
24046
24047            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
24048            for (File file : files) {
24049                final String packageName = file.getName();
24050                try {
24051                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24052                } catch (PackageManagerException e) {
24053                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24054                    try {
24055                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24056                                StorageManager.FLAG_STORAGE_CE, 0);
24057                    } catch (InstallerException e2) {
24058                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24059                    }
24060                }
24061            }
24062        }
24063        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
24064            final File[] files = FileUtils.listFilesOrEmpty(deDir);
24065            for (File file : files) {
24066                final String packageName = file.getName();
24067                try {
24068                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24069                } catch (PackageManagerException e) {
24070                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24071                    try {
24072                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24073                                StorageManager.FLAG_STORAGE_DE, 0);
24074                    } catch (InstallerException e2) {
24075                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24076                    }
24077                }
24078            }
24079        }
24080
24081        // Ensure that data directories are ready to roll for all packages
24082        // installed for this volume and user
24083        final List<PackageSetting> packages;
24084        synchronized (mPackages) {
24085            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24086        }
24087        int preparedCount = 0;
24088        for (PackageSetting ps : packages) {
24089            final String packageName = ps.name;
24090            if (ps.pkg == null) {
24091                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24092                // TODO: might be due to legacy ASEC apps; we should circle back
24093                // and reconcile again once they're scanned
24094                continue;
24095            }
24096            // Skip non-core apps if requested
24097            if (onlyCoreApps && !ps.pkg.coreApp) {
24098                result.add(packageName);
24099                continue;
24100            }
24101
24102            if (ps.getInstalled(userId)) {
24103                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24104                preparedCount++;
24105            }
24106        }
24107
24108        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24109        return result;
24110    }
24111
24112    /**
24113     * Prepare app data for the given app just after it was installed or
24114     * upgraded. This method carefully only touches users that it's installed
24115     * for, and it forces a restorecon to handle any seinfo changes.
24116     * <p>
24117     * Verifies that directories exist and that ownership and labeling is
24118     * correct for all installed apps. If there is an ownership mismatch, it
24119     * will try recovering system apps by wiping data; third-party app data is
24120     * left intact.
24121     * <p>
24122     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24123     */
24124    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24125        final PackageSetting ps;
24126        synchronized (mPackages) {
24127            ps = mSettings.mPackages.get(pkg.packageName);
24128            mSettings.writeKernelMappingLPr(ps);
24129        }
24130
24131        final UserManager um = mContext.getSystemService(UserManager.class);
24132        UserManagerInternal umInternal = getUserManagerInternal();
24133        for (UserInfo user : um.getUsers()) {
24134            final int flags;
24135            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24136                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24137            } else if (umInternal.isUserRunning(user.id)) {
24138                flags = StorageManager.FLAG_STORAGE_DE;
24139            } else {
24140                continue;
24141            }
24142
24143            if (ps.getInstalled(user.id)) {
24144                // TODO: when user data is locked, mark that we're still dirty
24145                prepareAppDataLIF(pkg, user.id, flags);
24146            }
24147        }
24148    }
24149
24150    /**
24151     * Prepare app data for the given app.
24152     * <p>
24153     * Verifies that directories exist and that ownership and labeling is
24154     * correct for all installed apps. If there is an ownership mismatch, this
24155     * will try recovering system apps by wiping data; third-party app data is
24156     * left intact.
24157     */
24158    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24159        if (pkg == null) {
24160            Slog.wtf(TAG, "Package was null!", new Throwable());
24161            return;
24162        }
24163        prepareAppDataLeafLIF(pkg, userId, flags);
24164        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24165        for (int i = 0; i < childCount; i++) {
24166            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24167        }
24168    }
24169
24170    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24171            boolean maybeMigrateAppData) {
24172        prepareAppDataLIF(pkg, userId, flags);
24173
24174        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24175            // We may have just shuffled around app data directories, so
24176            // prepare them one more time
24177            prepareAppDataLIF(pkg, userId, flags);
24178        }
24179    }
24180
24181    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24182        if (DEBUG_APP_DATA) {
24183            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24184                    + Integer.toHexString(flags));
24185        }
24186
24187        final String volumeUuid = pkg.volumeUuid;
24188        final String packageName = pkg.packageName;
24189        final ApplicationInfo app = pkg.applicationInfo;
24190        final int appId = UserHandle.getAppId(app.uid);
24191
24192        Preconditions.checkNotNull(app.seInfo);
24193
24194        long ceDataInode = -1;
24195        try {
24196            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24197                    appId, app.seInfo, app.targetSdkVersion);
24198        } catch (InstallerException e) {
24199            if (app.isSystemApp()) {
24200                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24201                        + ", but trying to recover: " + e);
24202                destroyAppDataLeafLIF(pkg, userId, flags);
24203                try {
24204                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24205                            appId, app.seInfo, app.targetSdkVersion);
24206                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24207                } catch (InstallerException e2) {
24208                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24209                }
24210            } else {
24211                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24212            }
24213        }
24214
24215        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24216            // TODO: mark this structure as dirty so we persist it!
24217            synchronized (mPackages) {
24218                final PackageSetting ps = mSettings.mPackages.get(packageName);
24219                if (ps != null) {
24220                    ps.setCeDataInode(ceDataInode, userId);
24221                }
24222            }
24223        }
24224
24225        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24226    }
24227
24228    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24229        if (pkg == null) {
24230            Slog.wtf(TAG, "Package was null!", new Throwable());
24231            return;
24232        }
24233        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24234        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24235        for (int i = 0; i < childCount; i++) {
24236            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24237        }
24238    }
24239
24240    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24241        final String volumeUuid = pkg.volumeUuid;
24242        final String packageName = pkg.packageName;
24243        final ApplicationInfo app = pkg.applicationInfo;
24244
24245        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24246            // Create a native library symlink only if we have native libraries
24247            // and if the native libraries are 32 bit libraries. We do not provide
24248            // this symlink for 64 bit libraries.
24249            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24250                final String nativeLibPath = app.nativeLibraryDir;
24251                try {
24252                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24253                            nativeLibPath, userId);
24254                } catch (InstallerException e) {
24255                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24256                }
24257            }
24258        }
24259    }
24260
24261    /**
24262     * For system apps on non-FBE devices, this method migrates any existing
24263     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24264     * requested by the app.
24265     */
24266    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24267        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24268                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24269            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24270                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24271            try {
24272                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24273                        storageTarget);
24274            } catch (InstallerException e) {
24275                logCriticalInfo(Log.WARN,
24276                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24277            }
24278            return true;
24279        } else {
24280            return false;
24281        }
24282    }
24283
24284    public PackageFreezer freezePackage(String packageName, String killReason) {
24285        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24286    }
24287
24288    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24289        return new PackageFreezer(packageName, userId, killReason);
24290    }
24291
24292    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24293            String killReason) {
24294        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24295    }
24296
24297    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24298            String killReason) {
24299        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24300            return new PackageFreezer();
24301        } else {
24302            return freezePackage(packageName, userId, killReason);
24303        }
24304    }
24305
24306    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24307            String killReason) {
24308        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24309    }
24310
24311    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24312            String killReason) {
24313        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24314            return new PackageFreezer();
24315        } else {
24316            return freezePackage(packageName, userId, killReason);
24317        }
24318    }
24319
24320    /**
24321     * Class that freezes and kills the given package upon creation, and
24322     * unfreezes it upon closing. This is typically used when doing surgery on
24323     * app code/data to prevent the app from running while you're working.
24324     */
24325    private class PackageFreezer implements AutoCloseable {
24326        private final String mPackageName;
24327        private final PackageFreezer[] mChildren;
24328
24329        private final boolean mWeFroze;
24330
24331        private final AtomicBoolean mClosed = new AtomicBoolean();
24332        private final CloseGuard mCloseGuard = CloseGuard.get();
24333
24334        /**
24335         * Create and return a stub freezer that doesn't actually do anything,
24336         * typically used when someone requested
24337         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24338         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24339         */
24340        public PackageFreezer() {
24341            mPackageName = null;
24342            mChildren = null;
24343            mWeFroze = false;
24344            mCloseGuard.open("close");
24345        }
24346
24347        public PackageFreezer(String packageName, int userId, String killReason) {
24348            synchronized (mPackages) {
24349                mPackageName = packageName;
24350                mWeFroze = mFrozenPackages.add(mPackageName);
24351
24352                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24353                if (ps != null) {
24354                    killApplication(ps.name, ps.appId, userId, killReason);
24355                }
24356
24357                final PackageParser.Package p = mPackages.get(packageName);
24358                if (p != null && p.childPackages != null) {
24359                    final int N = p.childPackages.size();
24360                    mChildren = new PackageFreezer[N];
24361                    for (int i = 0; i < N; i++) {
24362                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24363                                userId, killReason);
24364                    }
24365                } else {
24366                    mChildren = null;
24367                }
24368            }
24369            mCloseGuard.open("close");
24370        }
24371
24372        @Override
24373        protected void finalize() throws Throwable {
24374            try {
24375                if (mCloseGuard != null) {
24376                    mCloseGuard.warnIfOpen();
24377                }
24378
24379                close();
24380            } finally {
24381                super.finalize();
24382            }
24383        }
24384
24385        @Override
24386        public void close() {
24387            mCloseGuard.close();
24388            if (mClosed.compareAndSet(false, true)) {
24389                synchronized (mPackages) {
24390                    if (mWeFroze) {
24391                        mFrozenPackages.remove(mPackageName);
24392                    }
24393
24394                    if (mChildren != null) {
24395                        for (PackageFreezer freezer : mChildren) {
24396                            freezer.close();
24397                        }
24398                    }
24399                }
24400            }
24401        }
24402    }
24403
24404    /**
24405     * Verify that given package is currently frozen.
24406     */
24407    private void checkPackageFrozen(String packageName) {
24408        synchronized (mPackages) {
24409            if (!mFrozenPackages.contains(packageName)) {
24410                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24411            }
24412        }
24413    }
24414
24415    @Override
24416    public int movePackage(final String packageName, final String volumeUuid) {
24417        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24418
24419        final int callingUid = Binder.getCallingUid();
24420        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24421        final int moveId = mNextMoveId.getAndIncrement();
24422        mHandler.post(new Runnable() {
24423            @Override
24424            public void run() {
24425                try {
24426                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24427                } catch (PackageManagerException e) {
24428                    Slog.w(TAG, "Failed to move " + packageName, e);
24429                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24430                }
24431            }
24432        });
24433        return moveId;
24434    }
24435
24436    private void movePackageInternal(final String packageName, final String volumeUuid,
24437            final int moveId, final int callingUid, UserHandle user)
24438                    throws PackageManagerException {
24439        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24440        final PackageManager pm = mContext.getPackageManager();
24441
24442        final boolean currentAsec;
24443        final String currentVolumeUuid;
24444        final File codeFile;
24445        final String installerPackageName;
24446        final String packageAbiOverride;
24447        final int appId;
24448        final String seinfo;
24449        final String label;
24450        final int targetSdkVersion;
24451        final PackageFreezer freezer;
24452        final int[] installedUserIds;
24453
24454        // reader
24455        synchronized (mPackages) {
24456            final PackageParser.Package pkg = mPackages.get(packageName);
24457            final PackageSetting ps = mSettings.mPackages.get(packageName);
24458            if (pkg == null
24459                    || ps == null
24460                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24461                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24462            }
24463            if (pkg.applicationInfo.isSystemApp()) {
24464                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24465                        "Cannot move system application");
24466            }
24467
24468            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24469            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24470                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24471            if (isInternalStorage && !allow3rdPartyOnInternal) {
24472                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24473                        "3rd party apps are not allowed on internal storage");
24474            }
24475
24476            if (pkg.applicationInfo.isExternalAsec()) {
24477                currentAsec = true;
24478                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24479            } else if (pkg.applicationInfo.isForwardLocked()) {
24480                currentAsec = true;
24481                currentVolumeUuid = "forward_locked";
24482            } else {
24483                currentAsec = false;
24484                currentVolumeUuid = ps.volumeUuid;
24485
24486                final File probe = new File(pkg.codePath);
24487                final File probeOat = new File(probe, "oat");
24488                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24489                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24490                            "Move only supported for modern cluster style installs");
24491                }
24492            }
24493
24494            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24495                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24496                        "Package already moved to " + volumeUuid);
24497            }
24498            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24499                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24500                        "Device admin cannot be moved");
24501            }
24502
24503            if (mFrozenPackages.contains(packageName)) {
24504                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24505                        "Failed to move already frozen package");
24506            }
24507
24508            codeFile = new File(pkg.codePath);
24509            installerPackageName = ps.installerPackageName;
24510            packageAbiOverride = ps.cpuAbiOverrideString;
24511            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24512            seinfo = pkg.applicationInfo.seInfo;
24513            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24514            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24515            freezer = freezePackage(packageName, "movePackageInternal");
24516            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24517        }
24518
24519        final Bundle extras = new Bundle();
24520        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24521        extras.putString(Intent.EXTRA_TITLE, label);
24522        mMoveCallbacks.notifyCreated(moveId, extras);
24523
24524        int installFlags;
24525        final boolean moveCompleteApp;
24526        final File measurePath;
24527
24528        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24529            installFlags = INSTALL_INTERNAL;
24530            moveCompleteApp = !currentAsec;
24531            measurePath = Environment.getDataAppDirectory(volumeUuid);
24532        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24533            installFlags = INSTALL_EXTERNAL;
24534            moveCompleteApp = false;
24535            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24536        } else {
24537            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24538            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24539                    || !volume.isMountedWritable()) {
24540                freezer.close();
24541                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24542                        "Move location not mounted private volume");
24543            }
24544
24545            Preconditions.checkState(!currentAsec);
24546
24547            installFlags = INSTALL_INTERNAL;
24548            moveCompleteApp = true;
24549            measurePath = Environment.getDataAppDirectory(volumeUuid);
24550        }
24551
24552        // If we're moving app data around, we need all the users unlocked
24553        if (moveCompleteApp) {
24554            for (int userId : installedUserIds) {
24555                if (StorageManager.isFileEncryptedNativeOrEmulated()
24556                        && !StorageManager.isUserKeyUnlocked(userId)) {
24557                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24558                            "User " + userId + " must be unlocked");
24559                }
24560            }
24561        }
24562
24563        final PackageStats stats = new PackageStats(null, -1);
24564        synchronized (mInstaller) {
24565            for (int userId : installedUserIds) {
24566                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24567                    freezer.close();
24568                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24569                            "Failed to measure package size");
24570                }
24571            }
24572        }
24573
24574        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24575                + stats.dataSize);
24576
24577        final long startFreeBytes = measurePath.getUsableSpace();
24578        final long sizeBytes;
24579        if (moveCompleteApp) {
24580            sizeBytes = stats.codeSize + stats.dataSize;
24581        } else {
24582            sizeBytes = stats.codeSize;
24583        }
24584
24585        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24586            freezer.close();
24587            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24588                    "Not enough free space to move");
24589        }
24590
24591        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24592
24593        final CountDownLatch installedLatch = new CountDownLatch(1);
24594        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24595            @Override
24596            public void onUserActionRequired(Intent intent) throws RemoteException {
24597                throw new IllegalStateException();
24598            }
24599
24600            @Override
24601            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24602                    Bundle extras) throws RemoteException {
24603                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24604                        + PackageManager.installStatusToString(returnCode, msg));
24605
24606                installedLatch.countDown();
24607                freezer.close();
24608
24609                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24610                switch (status) {
24611                    case PackageInstaller.STATUS_SUCCESS:
24612                        mMoveCallbacks.notifyStatusChanged(moveId,
24613                                PackageManager.MOVE_SUCCEEDED);
24614                        break;
24615                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24616                        mMoveCallbacks.notifyStatusChanged(moveId,
24617                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24618                        break;
24619                    default:
24620                        mMoveCallbacks.notifyStatusChanged(moveId,
24621                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24622                        break;
24623                }
24624            }
24625        };
24626
24627        final MoveInfo move;
24628        if (moveCompleteApp) {
24629            // Kick off a thread to report progress estimates
24630            new Thread() {
24631                @Override
24632                public void run() {
24633                    while (true) {
24634                        try {
24635                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24636                                break;
24637                            }
24638                        } catch (InterruptedException ignored) {
24639                        }
24640
24641                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24642                        final int progress = 10 + (int) MathUtils.constrain(
24643                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24644                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24645                    }
24646                }
24647            }.start();
24648
24649            final String dataAppName = codeFile.getName();
24650            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24651                    dataAppName, appId, seinfo, targetSdkVersion);
24652        } else {
24653            move = null;
24654        }
24655
24656        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24657
24658        final Message msg = mHandler.obtainMessage(INIT_COPY);
24659        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24660        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24661                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24662                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24663                PackageManager.INSTALL_REASON_UNKNOWN);
24664        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24665        msg.obj = params;
24666
24667        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24668                System.identityHashCode(msg.obj));
24669        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24670                System.identityHashCode(msg.obj));
24671
24672        mHandler.sendMessage(msg);
24673    }
24674
24675    @Override
24676    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24677        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24678
24679        final int realMoveId = mNextMoveId.getAndIncrement();
24680        final Bundle extras = new Bundle();
24681        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24682        mMoveCallbacks.notifyCreated(realMoveId, extras);
24683
24684        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24685            @Override
24686            public void onCreated(int moveId, Bundle extras) {
24687                // Ignored
24688            }
24689
24690            @Override
24691            public void onStatusChanged(int moveId, int status, long estMillis) {
24692                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24693            }
24694        };
24695
24696        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24697        storage.setPrimaryStorageUuid(volumeUuid, callback);
24698        return realMoveId;
24699    }
24700
24701    @Override
24702    public int getMoveStatus(int moveId) {
24703        mContext.enforceCallingOrSelfPermission(
24704                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24705        return mMoveCallbacks.mLastStatus.get(moveId);
24706    }
24707
24708    @Override
24709    public void registerMoveCallback(IPackageMoveObserver callback) {
24710        mContext.enforceCallingOrSelfPermission(
24711                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24712        mMoveCallbacks.register(callback);
24713    }
24714
24715    @Override
24716    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24717        mContext.enforceCallingOrSelfPermission(
24718                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24719        mMoveCallbacks.unregister(callback);
24720    }
24721
24722    @Override
24723    public boolean setInstallLocation(int loc) {
24724        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24725                null);
24726        if (getInstallLocation() == loc) {
24727            return true;
24728        }
24729        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24730                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24731            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24732                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24733            return true;
24734        }
24735        return false;
24736   }
24737
24738    @Override
24739    public int getInstallLocation() {
24740        // allow instant app access
24741        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24742                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24743                PackageHelper.APP_INSTALL_AUTO);
24744    }
24745
24746    /** Called by UserManagerService */
24747    void cleanUpUser(UserManagerService userManager, int userHandle) {
24748        synchronized (mPackages) {
24749            mDirtyUsers.remove(userHandle);
24750            mUserNeedsBadging.delete(userHandle);
24751            mSettings.removeUserLPw(userHandle);
24752            mPendingBroadcasts.remove(userHandle);
24753            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24754            removeUnusedPackagesLPw(userManager, userHandle);
24755        }
24756    }
24757
24758    /**
24759     * We're removing userHandle and would like to remove any downloaded packages
24760     * that are no longer in use by any other user.
24761     * @param userHandle the user being removed
24762     */
24763    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24764        final boolean DEBUG_CLEAN_APKS = false;
24765        int [] users = userManager.getUserIds();
24766        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24767        while (psit.hasNext()) {
24768            PackageSetting ps = psit.next();
24769            if (ps.pkg == null) {
24770                continue;
24771            }
24772            final String packageName = ps.pkg.packageName;
24773            // Skip over if system app
24774            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24775                continue;
24776            }
24777            if (DEBUG_CLEAN_APKS) {
24778                Slog.i(TAG, "Checking package " + packageName);
24779            }
24780            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24781            if (keep) {
24782                if (DEBUG_CLEAN_APKS) {
24783                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24784                }
24785            } else {
24786                for (int i = 0; i < users.length; i++) {
24787                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24788                        keep = true;
24789                        if (DEBUG_CLEAN_APKS) {
24790                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24791                                    + users[i]);
24792                        }
24793                        break;
24794                    }
24795                }
24796            }
24797            if (!keep) {
24798                if (DEBUG_CLEAN_APKS) {
24799                    Slog.i(TAG, "  Removing package " + packageName);
24800                }
24801                mHandler.post(new Runnable() {
24802                    public void run() {
24803                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24804                                userHandle, 0);
24805                    } //end run
24806                });
24807            }
24808        }
24809    }
24810
24811    /** Called by UserManagerService */
24812    void createNewUser(int userId, String[] disallowedPackages) {
24813        synchronized (mInstallLock) {
24814            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24815        }
24816        synchronized (mPackages) {
24817            scheduleWritePackageRestrictionsLocked(userId);
24818            scheduleWritePackageListLocked(userId);
24819            applyFactoryDefaultBrowserLPw(userId);
24820            primeDomainVerificationsLPw(userId);
24821        }
24822    }
24823
24824    void onNewUserCreated(final int userId) {
24825        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24826        // If permission review for legacy apps is required, we represent
24827        // dagerous permissions for such apps as always granted runtime
24828        // permissions to keep per user flag state whether review is needed.
24829        // Hence, if a new user is added we have to propagate dangerous
24830        // permission grants for these legacy apps.
24831        if (mPermissionReviewRequired) {
24832            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24833                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24834        }
24835    }
24836
24837    @Override
24838    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24839        mContext.enforceCallingOrSelfPermission(
24840                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24841                "Only package verification agents can read the verifier device identity");
24842
24843        synchronized (mPackages) {
24844            return mSettings.getVerifierDeviceIdentityLPw();
24845        }
24846    }
24847
24848    @Override
24849    public void setPermissionEnforced(String permission, boolean enforced) {
24850        // TODO: Now that we no longer change GID for storage, this should to away.
24851        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24852                "setPermissionEnforced");
24853        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24854            synchronized (mPackages) {
24855                if (mSettings.mReadExternalStorageEnforced == null
24856                        || mSettings.mReadExternalStorageEnforced != enforced) {
24857                    mSettings.mReadExternalStorageEnforced = enforced;
24858                    mSettings.writeLPr();
24859                }
24860            }
24861            // kill any non-foreground processes so we restart them and
24862            // grant/revoke the GID.
24863            final IActivityManager am = ActivityManager.getService();
24864            if (am != null) {
24865                final long token = Binder.clearCallingIdentity();
24866                try {
24867                    am.killProcessesBelowForeground("setPermissionEnforcement");
24868                } catch (RemoteException e) {
24869                } finally {
24870                    Binder.restoreCallingIdentity(token);
24871                }
24872            }
24873        } else {
24874            throw new IllegalArgumentException("No selective enforcement for " + permission);
24875        }
24876    }
24877
24878    @Override
24879    @Deprecated
24880    public boolean isPermissionEnforced(String permission) {
24881        // allow instant applications
24882        return true;
24883    }
24884
24885    @Override
24886    public boolean isStorageLow() {
24887        // allow instant applications
24888        final long token = Binder.clearCallingIdentity();
24889        try {
24890            final DeviceStorageMonitorInternal
24891                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24892            if (dsm != null) {
24893                return dsm.isMemoryLow();
24894            } else {
24895                return false;
24896            }
24897        } finally {
24898            Binder.restoreCallingIdentity(token);
24899        }
24900    }
24901
24902    @Override
24903    public IPackageInstaller getPackageInstaller() {
24904        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24905            return null;
24906        }
24907        return mInstallerService;
24908    }
24909
24910    private boolean userNeedsBadging(int userId) {
24911        int index = mUserNeedsBadging.indexOfKey(userId);
24912        if (index < 0) {
24913            final UserInfo userInfo;
24914            final long token = Binder.clearCallingIdentity();
24915            try {
24916                userInfo = sUserManager.getUserInfo(userId);
24917            } finally {
24918                Binder.restoreCallingIdentity(token);
24919            }
24920            final boolean b;
24921            if (userInfo != null && userInfo.isManagedProfile()) {
24922                b = true;
24923            } else {
24924                b = false;
24925            }
24926            mUserNeedsBadging.put(userId, b);
24927            return b;
24928        }
24929        return mUserNeedsBadging.valueAt(index);
24930    }
24931
24932    @Override
24933    public KeySet getKeySetByAlias(String packageName, String alias) {
24934        if (packageName == null || alias == null) {
24935            return null;
24936        }
24937        synchronized(mPackages) {
24938            final PackageParser.Package pkg = mPackages.get(packageName);
24939            if (pkg == null) {
24940                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24941                throw new IllegalArgumentException("Unknown package: " + packageName);
24942            }
24943            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24944            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24945                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24946                throw new IllegalArgumentException("Unknown package: " + packageName);
24947            }
24948            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24949            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24950        }
24951    }
24952
24953    @Override
24954    public KeySet getSigningKeySet(String packageName) {
24955        if (packageName == null) {
24956            return null;
24957        }
24958        synchronized(mPackages) {
24959            final int callingUid = Binder.getCallingUid();
24960            final int callingUserId = UserHandle.getUserId(callingUid);
24961            final PackageParser.Package pkg = mPackages.get(packageName);
24962            if (pkg == null) {
24963                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24964                throw new IllegalArgumentException("Unknown package: " + packageName);
24965            }
24966            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24967            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24968                // filter and pretend the package doesn't exist
24969                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24970                        + ", uid:" + callingUid);
24971                throw new IllegalArgumentException("Unknown package: " + packageName);
24972            }
24973            if (pkg.applicationInfo.uid != callingUid
24974                    && Process.SYSTEM_UID != callingUid) {
24975                throw new SecurityException("May not access signing KeySet of other apps.");
24976            }
24977            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24978            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24979        }
24980    }
24981
24982    @Override
24983    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24984        final int callingUid = Binder.getCallingUid();
24985        if (getInstantAppPackageName(callingUid) != null) {
24986            return false;
24987        }
24988        if (packageName == null || ks == null) {
24989            return false;
24990        }
24991        synchronized(mPackages) {
24992            final PackageParser.Package pkg = mPackages.get(packageName);
24993            if (pkg == null
24994                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24995                            UserHandle.getUserId(callingUid))) {
24996                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24997                throw new IllegalArgumentException("Unknown package: " + packageName);
24998            }
24999            IBinder ksh = ks.getToken();
25000            if (ksh instanceof KeySetHandle) {
25001                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25002                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
25003            }
25004            return false;
25005        }
25006    }
25007
25008    @Override
25009    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
25010        final int callingUid = Binder.getCallingUid();
25011        if (getInstantAppPackageName(callingUid) != null) {
25012            return false;
25013        }
25014        if (packageName == null || ks == null) {
25015            return false;
25016        }
25017        synchronized(mPackages) {
25018            final PackageParser.Package pkg = mPackages.get(packageName);
25019            if (pkg == null
25020                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25021                            UserHandle.getUserId(callingUid))) {
25022                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25023                throw new IllegalArgumentException("Unknown package: " + packageName);
25024            }
25025            IBinder ksh = ks.getToken();
25026            if (ksh instanceof KeySetHandle) {
25027                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25028                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
25029            }
25030            return false;
25031        }
25032    }
25033
25034    private void deletePackageIfUnusedLPr(final String packageName) {
25035        PackageSetting ps = mSettings.mPackages.get(packageName);
25036        if (ps == null) {
25037            return;
25038        }
25039        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
25040            // TODO Implement atomic delete if package is unused
25041            // It is currently possible that the package will be deleted even if it is installed
25042            // after this method returns.
25043            mHandler.post(new Runnable() {
25044                public void run() {
25045                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
25046                            0, PackageManager.DELETE_ALL_USERS);
25047                }
25048            });
25049        }
25050    }
25051
25052    /**
25053     * Check and throw if the given before/after packages would be considered a
25054     * downgrade.
25055     */
25056    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
25057            throws PackageManagerException {
25058        if (after.versionCode < before.mVersionCode) {
25059            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25060                    "Update version code " + after.versionCode + " is older than current "
25061                    + before.mVersionCode);
25062        } else if (after.versionCode == before.mVersionCode) {
25063            if (after.baseRevisionCode < before.baseRevisionCode) {
25064                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25065                        "Update base revision code " + after.baseRevisionCode
25066                        + " is older than current " + before.baseRevisionCode);
25067            }
25068
25069            if (!ArrayUtils.isEmpty(after.splitNames)) {
25070                for (int i = 0; i < after.splitNames.length; i++) {
25071                    final String splitName = after.splitNames[i];
25072                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25073                    if (j != -1) {
25074                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25075                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25076                                    "Update split " + splitName + " revision code "
25077                                    + after.splitRevisionCodes[i] + " is older than current "
25078                                    + before.splitRevisionCodes[j]);
25079                        }
25080                    }
25081                }
25082            }
25083        }
25084    }
25085
25086    private static class MoveCallbacks extends Handler {
25087        private static final int MSG_CREATED = 1;
25088        private static final int MSG_STATUS_CHANGED = 2;
25089
25090        private final RemoteCallbackList<IPackageMoveObserver>
25091                mCallbacks = new RemoteCallbackList<>();
25092
25093        private final SparseIntArray mLastStatus = new SparseIntArray();
25094
25095        public MoveCallbacks(Looper looper) {
25096            super(looper);
25097        }
25098
25099        public void register(IPackageMoveObserver callback) {
25100            mCallbacks.register(callback);
25101        }
25102
25103        public void unregister(IPackageMoveObserver callback) {
25104            mCallbacks.unregister(callback);
25105        }
25106
25107        @Override
25108        public void handleMessage(Message msg) {
25109            final SomeArgs args = (SomeArgs) msg.obj;
25110            final int n = mCallbacks.beginBroadcast();
25111            for (int i = 0; i < n; i++) {
25112                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25113                try {
25114                    invokeCallback(callback, msg.what, args);
25115                } catch (RemoteException ignored) {
25116                }
25117            }
25118            mCallbacks.finishBroadcast();
25119            args.recycle();
25120        }
25121
25122        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25123                throws RemoteException {
25124            switch (what) {
25125                case MSG_CREATED: {
25126                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25127                    break;
25128                }
25129                case MSG_STATUS_CHANGED: {
25130                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25131                    break;
25132                }
25133            }
25134        }
25135
25136        private void notifyCreated(int moveId, Bundle extras) {
25137            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25138
25139            final SomeArgs args = SomeArgs.obtain();
25140            args.argi1 = moveId;
25141            args.arg2 = extras;
25142            obtainMessage(MSG_CREATED, args).sendToTarget();
25143        }
25144
25145        private void notifyStatusChanged(int moveId, int status) {
25146            notifyStatusChanged(moveId, status, -1);
25147        }
25148
25149        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25150            Slog.v(TAG, "Move " + moveId + " status " + status);
25151
25152            final SomeArgs args = SomeArgs.obtain();
25153            args.argi1 = moveId;
25154            args.argi2 = status;
25155            args.arg3 = estMillis;
25156            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25157
25158            synchronized (mLastStatus) {
25159                mLastStatus.put(moveId, status);
25160            }
25161        }
25162    }
25163
25164    private final static class OnPermissionChangeListeners extends Handler {
25165        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25166
25167        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25168                new RemoteCallbackList<>();
25169
25170        public OnPermissionChangeListeners(Looper looper) {
25171            super(looper);
25172        }
25173
25174        @Override
25175        public void handleMessage(Message msg) {
25176            switch (msg.what) {
25177                case MSG_ON_PERMISSIONS_CHANGED: {
25178                    final int uid = msg.arg1;
25179                    handleOnPermissionsChanged(uid);
25180                } break;
25181            }
25182        }
25183
25184        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25185            mPermissionListeners.register(listener);
25186
25187        }
25188
25189        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25190            mPermissionListeners.unregister(listener);
25191        }
25192
25193        public void onPermissionsChanged(int uid) {
25194            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25195                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25196            }
25197        }
25198
25199        private void handleOnPermissionsChanged(int uid) {
25200            final int count = mPermissionListeners.beginBroadcast();
25201            try {
25202                for (int i = 0; i < count; i++) {
25203                    IOnPermissionsChangeListener callback = mPermissionListeners
25204                            .getBroadcastItem(i);
25205                    try {
25206                        callback.onPermissionsChanged(uid);
25207                    } catch (RemoteException e) {
25208                        Log.e(TAG, "Permission listener is dead", e);
25209                    }
25210                }
25211            } finally {
25212                mPermissionListeners.finishBroadcast();
25213            }
25214        }
25215    }
25216
25217    private class PackageManagerNative extends IPackageManagerNative.Stub {
25218        @Override
25219        public String[] getNamesForUids(int[] uids) throws RemoteException {
25220            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25221            // massage results so they can be parsed by the native binder
25222            for (int i = results.length - 1; i >= 0; --i) {
25223                if (results[i] == null) {
25224                    results[i] = "";
25225                }
25226            }
25227            return results;
25228        }
25229
25230        // NB: this differentiates between preloads and sideloads
25231        @Override
25232        public String getInstallerForPackage(String packageName) throws RemoteException {
25233            final String installerName = getInstallerPackageName(packageName);
25234            if (!TextUtils.isEmpty(installerName)) {
25235                return installerName;
25236            }
25237            // differentiate between preload and sideload
25238            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25239            ApplicationInfo appInfo = getApplicationInfo(packageName,
25240                                    /*flags*/ 0,
25241                                    /*userId*/ callingUser);
25242            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25243                return "preload";
25244            }
25245            return "";
25246        }
25247
25248        @Override
25249        public int getVersionCodeForPackage(String packageName) throws RemoteException {
25250            try {
25251                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25252                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25253                if (pInfo != null) {
25254                    return pInfo.versionCode;
25255                }
25256            } catch (Exception e) {
25257            }
25258            return 0;
25259        }
25260    }
25261
25262    private class PackageManagerInternalImpl extends PackageManagerInternal {
25263        @Override
25264        public void setLocationPackagesProvider(PackagesProvider provider) {
25265            synchronized (mPackages) {
25266                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25267            }
25268        }
25269
25270        @Override
25271        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25272            synchronized (mPackages) {
25273                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25274            }
25275        }
25276
25277        @Override
25278        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25279            synchronized (mPackages) {
25280                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25281            }
25282        }
25283
25284        @Override
25285        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25286            synchronized (mPackages) {
25287                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25288            }
25289        }
25290
25291        @Override
25292        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25293            synchronized (mPackages) {
25294                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25295            }
25296        }
25297
25298        @Override
25299        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25300            synchronized (mPackages) {
25301                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25302            }
25303        }
25304
25305        @Override
25306        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25307            synchronized (mPackages) {
25308                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25309                        packageName, userId);
25310            }
25311        }
25312
25313        @Override
25314        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25315            synchronized (mPackages) {
25316                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25317                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25318                        packageName, userId);
25319            }
25320        }
25321
25322        @Override
25323        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25324            synchronized (mPackages) {
25325                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25326                        packageName, userId);
25327            }
25328        }
25329
25330        @Override
25331        public void setKeepUninstalledPackages(final List<String> packageList) {
25332            Preconditions.checkNotNull(packageList);
25333            List<String> removedFromList = null;
25334            synchronized (mPackages) {
25335                if (mKeepUninstalledPackages != null) {
25336                    final int packagesCount = mKeepUninstalledPackages.size();
25337                    for (int i = 0; i < packagesCount; i++) {
25338                        String oldPackage = mKeepUninstalledPackages.get(i);
25339                        if (packageList != null && packageList.contains(oldPackage)) {
25340                            continue;
25341                        }
25342                        if (removedFromList == null) {
25343                            removedFromList = new ArrayList<>();
25344                        }
25345                        removedFromList.add(oldPackage);
25346                    }
25347                }
25348                mKeepUninstalledPackages = new ArrayList<>(packageList);
25349                if (removedFromList != null) {
25350                    final int removedCount = removedFromList.size();
25351                    for (int i = 0; i < removedCount; i++) {
25352                        deletePackageIfUnusedLPr(removedFromList.get(i));
25353                    }
25354                }
25355            }
25356        }
25357
25358        @Override
25359        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25360            synchronized (mPackages) {
25361                // If we do not support permission review, done.
25362                if (!mPermissionReviewRequired) {
25363                    return false;
25364                }
25365
25366                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25367                if (packageSetting == null) {
25368                    return false;
25369                }
25370
25371                // Permission review applies only to apps not supporting the new permission model.
25372                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25373                    return false;
25374                }
25375
25376                // Legacy apps have the permission and get user consent on launch.
25377                PermissionsState permissionsState = packageSetting.getPermissionsState();
25378                return permissionsState.isPermissionReviewRequired(userId);
25379            }
25380        }
25381
25382        @Override
25383        public PackageInfo getPackageInfo(
25384                String packageName, int flags, int filterCallingUid, int userId) {
25385            return PackageManagerService.this
25386                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25387                            flags, filterCallingUid, userId);
25388        }
25389
25390        @Override
25391        public ApplicationInfo getApplicationInfo(
25392                String packageName, int flags, int filterCallingUid, int userId) {
25393            return PackageManagerService.this
25394                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25395        }
25396
25397        @Override
25398        public ActivityInfo getActivityInfo(
25399                ComponentName component, int flags, int filterCallingUid, int userId) {
25400            return PackageManagerService.this
25401                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25402        }
25403
25404        @Override
25405        public List<ResolveInfo> queryIntentActivities(
25406                Intent intent, int flags, int filterCallingUid, int userId) {
25407            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25408            return PackageManagerService.this
25409                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25410                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25411        }
25412
25413        @Override
25414        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25415                int userId) {
25416            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25417        }
25418
25419        @Override
25420        public void setDeviceAndProfileOwnerPackages(
25421                int deviceOwnerUserId, String deviceOwnerPackage,
25422                SparseArray<String> profileOwnerPackages) {
25423            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25424                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25425        }
25426
25427        @Override
25428        public boolean isPackageDataProtected(int userId, String packageName) {
25429            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25430        }
25431
25432        @Override
25433        public boolean isPackageEphemeral(int userId, String packageName) {
25434            synchronized (mPackages) {
25435                final PackageSetting ps = mSettings.mPackages.get(packageName);
25436                return ps != null ? ps.getInstantApp(userId) : false;
25437            }
25438        }
25439
25440        @Override
25441        public boolean wasPackageEverLaunched(String packageName, int userId) {
25442            synchronized (mPackages) {
25443                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25444            }
25445        }
25446
25447        @Override
25448        public void grantRuntimePermission(String packageName, String name, int userId,
25449                boolean overridePolicy) {
25450            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25451                    overridePolicy);
25452        }
25453
25454        @Override
25455        public void revokeRuntimePermission(String packageName, String name, int userId,
25456                boolean overridePolicy) {
25457            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25458                    overridePolicy);
25459        }
25460
25461        @Override
25462        public String getNameForUid(int uid) {
25463            return PackageManagerService.this.getNameForUid(uid);
25464        }
25465
25466        @Override
25467        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25468                Intent origIntent, String resolvedType, String callingPackage,
25469                Bundle verificationBundle, int userId) {
25470            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25471                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25472                    userId);
25473        }
25474
25475        @Override
25476        public void grantEphemeralAccess(int userId, Intent intent,
25477                int targetAppId, int ephemeralAppId) {
25478            synchronized (mPackages) {
25479                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25480                        targetAppId, ephemeralAppId);
25481            }
25482        }
25483
25484        @Override
25485        public boolean isInstantAppInstallerComponent(ComponentName component) {
25486            synchronized (mPackages) {
25487                return mInstantAppInstallerActivity != null
25488                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25489            }
25490        }
25491
25492        @Override
25493        public void pruneInstantApps() {
25494            mInstantAppRegistry.pruneInstantApps();
25495        }
25496
25497        @Override
25498        public String getSetupWizardPackageName() {
25499            return mSetupWizardPackage;
25500        }
25501
25502        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25503            if (policy != null) {
25504                mExternalSourcesPolicy = policy;
25505            }
25506        }
25507
25508        @Override
25509        public boolean isPackagePersistent(String packageName) {
25510            synchronized (mPackages) {
25511                PackageParser.Package pkg = mPackages.get(packageName);
25512                return pkg != null
25513                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25514                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25515                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25516                        : false;
25517            }
25518        }
25519
25520        @Override
25521        public List<PackageInfo> getOverlayPackages(int userId) {
25522            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25523            synchronized (mPackages) {
25524                for (PackageParser.Package p : mPackages.values()) {
25525                    if (p.mOverlayTarget != null) {
25526                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25527                        if (pkg != null) {
25528                            overlayPackages.add(pkg);
25529                        }
25530                    }
25531                }
25532            }
25533            return overlayPackages;
25534        }
25535
25536        @Override
25537        public List<String> getTargetPackageNames(int userId) {
25538            List<String> targetPackages = new ArrayList<>();
25539            synchronized (mPackages) {
25540                for (PackageParser.Package p : mPackages.values()) {
25541                    if (p.mOverlayTarget == null) {
25542                        targetPackages.add(p.packageName);
25543                    }
25544                }
25545            }
25546            return targetPackages;
25547        }
25548
25549        @Override
25550        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25551                @Nullable List<String> overlayPackageNames) {
25552            synchronized (mPackages) {
25553                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25554                    Slog.e(TAG, "failed to find package " + targetPackageName);
25555                    return false;
25556                }
25557                ArrayList<String> overlayPaths = null;
25558                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25559                    final int N = overlayPackageNames.size();
25560                    overlayPaths = new ArrayList<>(N);
25561                    for (int i = 0; i < N; i++) {
25562                        final String packageName = overlayPackageNames.get(i);
25563                        final PackageParser.Package pkg = mPackages.get(packageName);
25564                        if (pkg == null) {
25565                            Slog.e(TAG, "failed to find package " + packageName);
25566                            return false;
25567                        }
25568                        overlayPaths.add(pkg.baseCodePath);
25569                    }
25570                }
25571
25572                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25573                ps.setOverlayPaths(overlayPaths, userId);
25574                return true;
25575            }
25576        }
25577
25578        @Override
25579        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25580                int flags, int userId) {
25581            return resolveIntentInternal(
25582                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25583        }
25584
25585        @Override
25586        public ResolveInfo resolveService(Intent intent, String resolvedType,
25587                int flags, int userId, int callingUid) {
25588            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25589        }
25590
25591        @Override
25592        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25593            synchronized (mPackages) {
25594                mIsolatedOwners.put(isolatedUid, ownerUid);
25595            }
25596        }
25597
25598        @Override
25599        public void removeIsolatedUid(int isolatedUid) {
25600            synchronized (mPackages) {
25601                mIsolatedOwners.delete(isolatedUid);
25602            }
25603        }
25604
25605        @Override
25606        public int getUidTargetSdkVersion(int uid) {
25607            synchronized (mPackages) {
25608                return getUidTargetSdkVersionLockedLPr(uid);
25609            }
25610        }
25611
25612        @Override
25613        public boolean canAccessInstantApps(int callingUid, int userId) {
25614            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25615        }
25616
25617        @Override
25618        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25619            synchronized (mPackages) {
25620                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25621            }
25622        }
25623
25624        @Override
25625        public void notifyPackageUse(String packageName, int reason) {
25626            synchronized (mPackages) {
25627                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25628            }
25629        }
25630    }
25631
25632    @Override
25633    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25634        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25635        synchronized (mPackages) {
25636            final long identity = Binder.clearCallingIdentity();
25637            try {
25638                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25639                        packageNames, userId);
25640            } finally {
25641                Binder.restoreCallingIdentity(identity);
25642            }
25643        }
25644    }
25645
25646    @Override
25647    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25648        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25649        synchronized (mPackages) {
25650            final long identity = Binder.clearCallingIdentity();
25651            try {
25652                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25653                        packageNames, userId);
25654            } finally {
25655                Binder.restoreCallingIdentity(identity);
25656            }
25657        }
25658    }
25659
25660    private static void enforceSystemOrPhoneCaller(String tag) {
25661        int callingUid = Binder.getCallingUid();
25662        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25663            throw new SecurityException(
25664                    "Cannot call " + tag + " from UID " + callingUid);
25665        }
25666    }
25667
25668    boolean isHistoricalPackageUsageAvailable() {
25669        return mPackageUsage.isHistoricalPackageUsageAvailable();
25670    }
25671
25672    /**
25673     * Return a <b>copy</b> of the collection of packages known to the package manager.
25674     * @return A copy of the values of mPackages.
25675     */
25676    Collection<PackageParser.Package> getPackages() {
25677        synchronized (mPackages) {
25678            return new ArrayList<>(mPackages.values());
25679        }
25680    }
25681
25682    /**
25683     * Logs process start information (including base APK hash) to the security log.
25684     * @hide
25685     */
25686    @Override
25687    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25688            String apkFile, int pid) {
25689        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25690            return;
25691        }
25692        if (!SecurityLog.isLoggingEnabled()) {
25693            return;
25694        }
25695        Bundle data = new Bundle();
25696        data.putLong("startTimestamp", System.currentTimeMillis());
25697        data.putString("processName", processName);
25698        data.putInt("uid", uid);
25699        data.putString("seinfo", seinfo);
25700        data.putString("apkFile", apkFile);
25701        data.putInt("pid", pid);
25702        Message msg = mProcessLoggingHandler.obtainMessage(
25703                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25704        msg.setData(data);
25705        mProcessLoggingHandler.sendMessage(msg);
25706    }
25707
25708    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25709        return mCompilerStats.getPackageStats(pkgName);
25710    }
25711
25712    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25713        return getOrCreateCompilerPackageStats(pkg.packageName);
25714    }
25715
25716    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25717        return mCompilerStats.getOrCreatePackageStats(pkgName);
25718    }
25719
25720    public void deleteCompilerPackageStats(String pkgName) {
25721        mCompilerStats.deletePackageStats(pkgName);
25722    }
25723
25724    @Override
25725    public int getInstallReason(String packageName, int userId) {
25726        final int callingUid = Binder.getCallingUid();
25727        enforceCrossUserPermission(callingUid, userId,
25728                true /* requireFullPermission */, false /* checkShell */,
25729                "get install reason");
25730        synchronized (mPackages) {
25731            final PackageSetting ps = mSettings.mPackages.get(packageName);
25732            if (filterAppAccessLPr(ps, callingUid, userId)) {
25733                return PackageManager.INSTALL_REASON_UNKNOWN;
25734            }
25735            if (ps != null) {
25736                return ps.getInstallReason(userId);
25737            }
25738        }
25739        return PackageManager.INSTALL_REASON_UNKNOWN;
25740    }
25741
25742    @Override
25743    public boolean canRequestPackageInstalls(String packageName, int userId) {
25744        return canRequestPackageInstallsInternal(packageName, 0, userId,
25745                true /* throwIfPermNotDeclared*/);
25746    }
25747
25748    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25749            boolean throwIfPermNotDeclared) {
25750        int callingUid = Binder.getCallingUid();
25751        int uid = getPackageUid(packageName, 0, userId);
25752        if (callingUid != uid && callingUid != Process.ROOT_UID
25753                && callingUid != Process.SYSTEM_UID) {
25754            throw new SecurityException(
25755                    "Caller uid " + callingUid + " does not own package " + packageName);
25756        }
25757        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25758        if (info == null) {
25759            return false;
25760        }
25761        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25762            return false;
25763        }
25764        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25765        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25766        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25767            if (throwIfPermNotDeclared) {
25768                throw new SecurityException("Need to declare " + appOpPermission
25769                        + " to call this api");
25770            } else {
25771                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25772                return false;
25773            }
25774        }
25775        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25776            return false;
25777        }
25778        if (mExternalSourcesPolicy != null) {
25779            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25780            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25781                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25782            }
25783        }
25784        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25785    }
25786
25787    @Override
25788    public ComponentName getInstantAppResolverSettingsComponent() {
25789        return mInstantAppResolverSettingsComponent;
25790    }
25791
25792    @Override
25793    public ComponentName getInstantAppInstallerComponent() {
25794        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25795            return null;
25796        }
25797        return mInstantAppInstallerActivity == null
25798                ? null : mInstantAppInstallerActivity.getComponentName();
25799    }
25800
25801    @Override
25802    public String getInstantAppAndroidId(String packageName, int userId) {
25803        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25804                "getInstantAppAndroidId");
25805        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25806                true /* requireFullPermission */, false /* checkShell */,
25807                "getInstantAppAndroidId");
25808        // Make sure the target is an Instant App.
25809        if (!isInstantApp(packageName, userId)) {
25810            return null;
25811        }
25812        synchronized (mPackages) {
25813            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25814        }
25815    }
25816
25817    boolean canHaveOatDir(String packageName) {
25818        synchronized (mPackages) {
25819            PackageParser.Package p = mPackages.get(packageName);
25820            if (p == null) {
25821                return false;
25822            }
25823            return p.canHaveOatDir();
25824        }
25825    }
25826
25827    private String getOatDir(PackageParser.Package pkg) {
25828        if (!pkg.canHaveOatDir()) {
25829            return null;
25830        }
25831        File codePath = new File(pkg.codePath);
25832        if (codePath.isDirectory()) {
25833            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25834        }
25835        return null;
25836    }
25837
25838    void deleteOatArtifactsOfPackage(String packageName) {
25839        final String[] instructionSets;
25840        final List<String> codePaths;
25841        final String oatDir;
25842        final PackageParser.Package pkg;
25843        synchronized (mPackages) {
25844            pkg = mPackages.get(packageName);
25845        }
25846        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25847        codePaths = pkg.getAllCodePaths();
25848        oatDir = getOatDir(pkg);
25849
25850        for (String codePath : codePaths) {
25851            for (String isa : instructionSets) {
25852                try {
25853                    mInstaller.deleteOdex(codePath, isa, oatDir);
25854                } catch (InstallerException e) {
25855                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25856                }
25857            }
25858        }
25859    }
25860
25861    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25862        Set<String> unusedPackages = new HashSet<>();
25863        long currentTimeInMillis = System.currentTimeMillis();
25864        synchronized (mPackages) {
25865            for (PackageParser.Package pkg : mPackages.values()) {
25866                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25867                if (ps == null) {
25868                    continue;
25869                }
25870                PackageDexUsage.PackageUseInfo packageUseInfo =
25871                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25872                if (PackageManagerServiceUtils
25873                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25874                                downgradeTimeThresholdMillis, packageUseInfo,
25875                                pkg.getLatestPackageUseTimeInMills(),
25876                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25877                    unusedPackages.add(pkg.packageName);
25878                }
25879            }
25880        }
25881        return unusedPackages;
25882    }
25883}
25884
25885interface PackageSender {
25886    void sendPackageBroadcast(final String action, final String pkg,
25887        final Bundle extras, final int flags, final String targetPkg,
25888        final IIntentReceiver finishedReceiver, final int[] userIds);
25889    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25890        boolean includeStopped, int appId, int... userIds);
25891}
25892