PackageManagerService.java revision 10e5eeb68d4a3c55d761e13016994a537c703c63
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.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67import static android.content.pm.PackageManager.MATCH_ALL;
68import static android.content.pm.PackageManager.MATCH_ANY_USER;
69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
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_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106
107import android.Manifest;
108import android.annotation.IntDef;
109import android.annotation.NonNull;
110import android.annotation.Nullable;
111import android.app.ActivityManager;
112import android.app.AppOpsManager;
113import android.app.IActivityManager;
114import android.app.ResourcesManager;
115import android.app.admin.IDevicePolicyManager;
116import android.app.admin.SecurityLog;
117import android.app.backup.IBackupManager;
118import android.content.BroadcastReceiver;
119import android.content.ComponentName;
120import android.content.ContentResolver;
121import android.content.Context;
122import android.content.IIntentReceiver;
123import android.content.Intent;
124import android.content.IntentFilter;
125import android.content.IntentSender;
126import android.content.IntentSender.SendIntentException;
127import android.content.ServiceConnection;
128import android.content.pm.ActivityInfo;
129import android.content.pm.ApplicationInfo;
130import android.content.pm.AppsQueryHelper;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.ChangedPackages;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IDexModuleRegisterCallback;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstantAppInfo;
146import android.content.pm.InstantAppRequest;
147import android.content.pm.InstantAppResolveInfo;
148import android.content.pm.InstrumentationInfo;
149import android.content.pm.IntentFilterVerificationInfo;
150import android.content.pm.KeySet;
151import android.content.pm.PackageCleanItem;
152import android.content.pm.PackageInfo;
153import android.content.pm.PackageInfoLite;
154import android.content.pm.PackageInstaller;
155import android.content.pm.PackageManager;
156import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
157import android.content.pm.PackageManagerInternal;
158import android.content.pm.PackageParser;
159import android.content.pm.PackageParser.ActivityIntentInfo;
160import android.content.pm.PackageParser.PackageLite;
161import android.content.pm.PackageParser.PackageParserException;
162import android.content.pm.PackageStats;
163import android.content.pm.PackageUserState;
164import android.content.pm.ParceledListSlice;
165import android.content.pm.PermissionGroupInfo;
166import android.content.pm.PermissionInfo;
167import android.content.pm.ProviderInfo;
168import android.content.pm.ResolveInfo;
169import android.content.pm.ServiceInfo;
170import android.content.pm.SharedLibraryInfo;
171import android.content.pm.Signature;
172import android.content.pm.UserInfo;
173import android.content.pm.VerifierDeviceIdentity;
174import android.content.pm.VerifierInfo;
175import android.content.pm.VersionedPackage;
176import android.content.res.Resources;
177import android.database.ContentObserver;
178import android.graphics.Bitmap;
179import android.hardware.display.DisplayManager;
180import android.net.Uri;
181import android.os.Binder;
182import android.os.Build;
183import android.os.Bundle;
184import android.os.Debug;
185import android.os.Environment;
186import android.os.Environment.UserEnvironment;
187import android.os.FileUtils;
188import android.os.Handler;
189import android.os.IBinder;
190import android.os.Looper;
191import android.os.Message;
192import android.os.Parcel;
193import android.os.ParcelFileDescriptor;
194import android.os.PatternMatcher;
195import android.os.Process;
196import android.os.RemoteCallbackList;
197import android.os.RemoteException;
198import android.os.ResultReceiver;
199import android.os.SELinux;
200import android.os.ServiceManager;
201import android.os.ShellCallback;
202import android.os.SystemClock;
203import android.os.SystemProperties;
204import android.os.Trace;
205import android.os.UserHandle;
206import android.os.UserManager;
207import android.os.UserManagerInternal;
208import android.os.storage.IStorageManager;
209import android.os.storage.StorageEventListener;
210import android.os.storage.StorageManager;
211import android.os.storage.StorageManagerInternal;
212import android.os.storage.VolumeInfo;
213import android.os.storage.VolumeRecord;
214import android.provider.Settings.Global;
215import android.provider.Settings.Secure;
216import android.security.KeyStore;
217import android.security.SystemKeyStore;
218import android.service.pm.PackageServiceDumpProto;
219import android.system.ErrnoException;
220import android.system.Os;
221import android.text.TextUtils;
222import android.text.format.DateUtils;
223import android.util.ArrayMap;
224import android.util.ArraySet;
225import android.util.Base64;
226import android.util.BootTimingsTraceLog;
227import android.util.DisplayMetrics;
228import android.util.EventLog;
229import android.util.ExceptionUtils;
230import android.util.Log;
231import android.util.LogPrinter;
232import android.util.MathUtils;
233import android.util.PackageUtils;
234import android.util.Pair;
235import android.util.PrintStreamPrinter;
236import android.util.Slog;
237import android.util.SparseArray;
238import android.util.SparseBooleanArray;
239import android.util.SparseIntArray;
240import android.util.Xml;
241import android.util.jar.StrictJarFile;
242import android.util.proto.ProtoOutputStream;
243import android.view.Display;
244
245import com.android.internal.R;
246import com.android.internal.annotations.GuardedBy;
247import com.android.internal.app.IMediaContainerService;
248import com.android.internal.app.ResolverActivity;
249import com.android.internal.content.NativeLibraryHelper;
250import com.android.internal.content.PackageHelper;
251import com.android.internal.logging.MetricsLogger;
252import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
253import com.android.internal.os.IParcelFileDescriptorFactory;
254import com.android.internal.os.RoSystemProperties;
255import com.android.internal.os.SomeArgs;
256import com.android.internal.os.Zygote;
257import com.android.internal.telephony.CarrierAppUtils;
258import com.android.internal.util.ArrayUtils;
259import com.android.internal.util.ConcurrentUtils;
260import com.android.internal.util.DumpUtils;
261import com.android.internal.util.FastPrintWriter;
262import com.android.internal.util.FastXmlSerializer;
263import com.android.internal.util.IndentingPrintWriter;
264import com.android.internal.util.Preconditions;
265import com.android.internal.util.XmlUtils;
266import com.android.server.AttributeCache;
267import com.android.server.DeviceIdleController;
268import com.android.server.EventLogTags;
269import com.android.server.FgThread;
270import com.android.server.IntentResolver;
271import com.android.server.LocalServices;
272import com.android.server.LockGuard;
273import com.android.server.ServiceThread;
274import com.android.server.SystemConfig;
275import com.android.server.SystemServerInitThreadPool;
276import com.android.server.Watchdog;
277import com.android.server.net.NetworkPolicyManagerInternal;
278import com.android.server.pm.Installer.InstallerException;
279import com.android.server.pm.PermissionsState.PermissionState;
280import com.android.server.pm.Settings.DatabaseVersion;
281import com.android.server.pm.Settings.VersionInfo;
282import com.android.server.pm.dex.DexManager;
283import com.android.server.pm.dex.DexoptOptions;
284import com.android.server.pm.dex.PackageDexUsage;
285import com.android.server.storage.DeviceStorageMonitorInternal;
286
287import dalvik.system.CloseGuard;
288import dalvik.system.DexFile;
289import dalvik.system.VMRuntime;
290
291import libcore.io.IoUtils;
292import libcore.util.EmptyArray;
293
294import org.xmlpull.v1.XmlPullParser;
295import org.xmlpull.v1.XmlPullParserException;
296import org.xmlpull.v1.XmlSerializer;
297
298import java.io.BufferedOutputStream;
299import java.io.BufferedReader;
300import java.io.ByteArrayInputStream;
301import java.io.ByteArrayOutputStream;
302import java.io.File;
303import java.io.FileDescriptor;
304import java.io.FileInputStream;
305import java.io.FileOutputStream;
306import java.io.FileReader;
307import java.io.FilenameFilter;
308import java.io.IOException;
309import java.io.PrintWriter;
310import java.lang.annotation.Retention;
311import java.lang.annotation.RetentionPolicy;
312import java.nio.charset.StandardCharsets;
313import java.security.DigestInputStream;
314import java.security.MessageDigest;
315import java.security.NoSuchAlgorithmException;
316import java.security.PublicKey;
317import java.security.SecureRandom;
318import java.security.cert.Certificate;
319import java.security.cert.CertificateEncodingException;
320import java.security.cert.CertificateException;
321import java.text.SimpleDateFormat;
322import java.util.ArrayList;
323import java.util.Arrays;
324import java.util.Collection;
325import java.util.Collections;
326import java.util.Comparator;
327import java.util.Date;
328import java.util.HashMap;
329import java.util.HashSet;
330import java.util.Iterator;
331import java.util.LinkedHashSet;
332import java.util.List;
333import java.util.Map;
334import java.util.Objects;
335import java.util.Set;
336import java.util.concurrent.CountDownLatch;
337import java.util.concurrent.Future;
338import java.util.concurrent.TimeUnit;
339import java.util.concurrent.atomic.AtomicBoolean;
340import java.util.concurrent.atomic.AtomicInteger;
341
342/**
343 * Keep track of all those APKs everywhere.
344 * <p>
345 * Internally there are two important locks:
346 * <ul>
347 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
348 * and other related state. It is a fine-grained lock that should only be held
349 * momentarily, as it's one of the most contended locks in the system.
350 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
351 * operations typically involve heavy lifting of application data on disk. Since
352 * {@code installd} is single-threaded, and it's operations can often be slow,
353 * this lock should never be acquired while already holding {@link #mPackages}.
354 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
355 * holding {@link #mInstallLock}.
356 * </ul>
357 * Many internal methods rely on the caller to hold the appropriate locks, and
358 * this contract is expressed through method name suffixes:
359 * <ul>
360 * <li>fooLI(): the caller must hold {@link #mInstallLock}
361 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
362 * being modified must be frozen
363 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
364 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
365 * </ul>
366 * <p>
367 * Because this class is very central to the platform's security; please run all
368 * CTS and unit tests whenever making modifications:
369 *
370 * <pre>
371 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
372 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
373 * </pre>
374 */
375public class PackageManagerService extends IPackageManager.Stub
376        implements PackageSender {
377    static final String TAG = "PackageManager";
378    static final boolean DEBUG_SETTINGS = false;
379    static final boolean DEBUG_PREFERRED = false;
380    static final boolean DEBUG_UPGRADE = false;
381    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
382    private static final boolean DEBUG_BACKUP = false;
383    private static final boolean DEBUG_INSTALL = false;
384    private static final boolean DEBUG_REMOVE = false;
385    private static final boolean DEBUG_BROADCASTS = false;
386    private static final boolean DEBUG_SHOW_INFO = false;
387    private static final boolean DEBUG_PACKAGE_INFO = false;
388    private static final boolean DEBUG_INTENT_MATCHING = false;
389    private static final boolean DEBUG_PACKAGE_SCANNING = false;
390    private static final boolean DEBUG_VERIFY = false;
391    private static final boolean DEBUG_FILTERS = false;
392    private static final boolean DEBUG_PERMISSIONS = false;
393    private static final boolean DEBUG_SHARED_LIBRARIES = false;
394
395    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
396    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
397    // user, but by default initialize to this.
398    public static final boolean DEBUG_DEXOPT = false;
399
400    private static final boolean DEBUG_ABI_SELECTION = false;
401    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
402    private static final boolean DEBUG_TRIAGED_MISSING = false;
403    private static final boolean DEBUG_APP_DATA = false;
404
405    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
406    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
407
408    private static final boolean HIDE_EPHEMERAL_APIS = false;
409
410    private static final boolean ENABLE_FREE_CACHE_V2 =
411            SystemProperties.getBoolean("fw.free_cache_v2", true);
412
413    private static final int RADIO_UID = Process.PHONE_UID;
414    private static final int LOG_UID = Process.LOG_UID;
415    private static final int NFC_UID = Process.NFC_UID;
416    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
417    private static final int SHELL_UID = Process.SHELL_UID;
418
419    // Cap the size of permission trees that 3rd party apps can define
420    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
421
422    // Suffix used during package installation when copying/moving
423    // package apks to install directory.
424    private static final String INSTALL_PACKAGE_SUFFIX = "-";
425
426    static final int SCAN_NO_DEX = 1<<1;
427    static final int SCAN_FORCE_DEX = 1<<2;
428    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
429    static final int SCAN_NEW_INSTALL = 1<<4;
430    static final int SCAN_UPDATE_TIME = 1<<5;
431    static final int SCAN_BOOTING = 1<<6;
432    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
433    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
434    static final int SCAN_REPLACING = 1<<9;
435    static final int SCAN_REQUIRE_KNOWN = 1<<10;
436    static final int SCAN_MOVE = 1<<11;
437    static final int SCAN_INITIAL = 1<<12;
438    static final int SCAN_CHECK_ONLY = 1<<13;
439    static final int SCAN_DONT_KILL_APP = 1<<14;
440    static final int SCAN_IGNORE_FROZEN = 1<<15;
441    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
442    static final int SCAN_AS_INSTANT_APP = 1<<17;
443    static final int SCAN_AS_FULL_APP = 1<<18;
444    /** Should not be with the scan flags */
445    static final int FLAGS_REMOVE_CHATTY = 1<<31;
446
447    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
448
449    private static final int[] EMPTY_INT_ARRAY = new int[0];
450
451    private static final int TYPE_UNKNOWN = 0;
452    private static final int TYPE_ACTIVITY = 1;
453    private static final int TYPE_RECEIVER = 2;
454    private static final int TYPE_SERVICE = 3;
455    private static final int TYPE_PROVIDER = 4;
456    @IntDef(prefix = { "TYPE_" }, value = {
457            TYPE_UNKNOWN,
458            TYPE_ACTIVITY,
459            TYPE_RECEIVER,
460            TYPE_SERVICE,
461            TYPE_PROVIDER,
462    })
463    @Retention(RetentionPolicy.SOURCE)
464    public @interface ComponentType {}
465
466    /**
467     * Timeout (in milliseconds) after which the watchdog should declare that
468     * our handler thread is wedged.  The usual default for such things is one
469     * minute but we sometimes do very lengthy I/O operations on this thread,
470     * such as installing multi-gigabyte applications, so ours needs to be longer.
471     */
472    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
473
474    /**
475     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
476     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
477     * settings entry if available, otherwise we use the hardcoded default.  If it's been
478     * more than this long since the last fstrim, we force one during the boot sequence.
479     *
480     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
481     * one gets run at the next available charging+idle time.  This final mandatory
482     * no-fstrim check kicks in only of the other scheduling criteria is never met.
483     */
484    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
485
486    /**
487     * Whether verification is enabled by default.
488     */
489    private static final boolean DEFAULT_VERIFY_ENABLE = true;
490
491    /**
492     * The default maximum time to wait for the verification agent to return in
493     * milliseconds.
494     */
495    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
496
497    /**
498     * The default response for package verification timeout.
499     *
500     * This can be either PackageManager.VERIFICATION_ALLOW or
501     * PackageManager.VERIFICATION_REJECT.
502     */
503    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
504
505    static final String PLATFORM_PACKAGE_NAME = "android";
506
507    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
508
509    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
510            DEFAULT_CONTAINER_PACKAGE,
511            "com.android.defcontainer.DefaultContainerService");
512
513    private static final String KILL_APP_REASON_GIDS_CHANGED =
514            "permission grant or revoke changed gids";
515
516    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
517            "permissions revoked";
518
519    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
520
521    private static final String PACKAGE_SCHEME = "package";
522
523    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
524
525    /** Permission grant: not grant the permission. */
526    private static final int GRANT_DENIED = 1;
527
528    /** Permission grant: grant the permission as an install permission. */
529    private static final int GRANT_INSTALL = 2;
530
531    /** Permission grant: grant the permission as a runtime one. */
532    private static final int GRANT_RUNTIME = 3;
533
534    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
535    private static final int GRANT_UPGRADE = 4;
536
537    /** Canonical intent used to identify what counts as a "web browser" app */
538    private static final Intent sBrowserIntent;
539    static {
540        sBrowserIntent = new Intent();
541        sBrowserIntent.setAction(Intent.ACTION_VIEW);
542        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
543        sBrowserIntent.setData(Uri.parse("http:"));
544    }
545
546    /**
547     * The set of all protected actions [i.e. those actions for which a high priority
548     * intent filter is disallowed].
549     */
550    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
551    static {
552        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
555        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
556    }
557
558    // Compilation reasons.
559    public static final int REASON_FIRST_BOOT = 0;
560    public static final int REASON_BOOT = 1;
561    public static final int REASON_INSTALL = 2;
562    public static final int REASON_BACKGROUND_DEXOPT = 3;
563    public static final int REASON_AB_OTA = 4;
564    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
565    public static final int REASON_SHARED = 6;
566
567    public static final int REASON_LAST = REASON_SHARED;
568
569    /** All dangerous permission names in the same order as the events in MetricsEvent */
570    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
571            Manifest.permission.READ_CALENDAR,
572            Manifest.permission.WRITE_CALENDAR,
573            Manifest.permission.CAMERA,
574            Manifest.permission.READ_CONTACTS,
575            Manifest.permission.WRITE_CONTACTS,
576            Manifest.permission.GET_ACCOUNTS,
577            Manifest.permission.ACCESS_FINE_LOCATION,
578            Manifest.permission.ACCESS_COARSE_LOCATION,
579            Manifest.permission.RECORD_AUDIO,
580            Manifest.permission.READ_PHONE_STATE,
581            Manifest.permission.CALL_PHONE,
582            Manifest.permission.READ_CALL_LOG,
583            Manifest.permission.WRITE_CALL_LOG,
584            Manifest.permission.ADD_VOICEMAIL,
585            Manifest.permission.USE_SIP,
586            Manifest.permission.PROCESS_OUTGOING_CALLS,
587            Manifest.permission.READ_CELL_BROADCASTS,
588            Manifest.permission.BODY_SENSORS,
589            Manifest.permission.SEND_SMS,
590            Manifest.permission.RECEIVE_SMS,
591            Manifest.permission.READ_SMS,
592            Manifest.permission.RECEIVE_WAP_PUSH,
593            Manifest.permission.RECEIVE_MMS,
594            Manifest.permission.READ_EXTERNAL_STORAGE,
595            Manifest.permission.WRITE_EXTERNAL_STORAGE,
596            Manifest.permission.READ_PHONE_NUMBERS,
597            Manifest.permission.ANSWER_PHONE_CALLS);
598
599
600    /**
601     * Version number for the package parser cache. Increment this whenever the format or
602     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
603     */
604    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
605
606    /**
607     * Whether the package parser cache is enabled.
608     */
609    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
610
611    final ServiceThread mHandlerThread;
612
613    final PackageHandler mHandler;
614
615    private final ProcessLoggingHandler mProcessLoggingHandler;
616
617    /**
618     * Messages for {@link #mHandler} that need to wait for system ready before
619     * being dispatched.
620     */
621    private ArrayList<Message> mPostSystemReadyMessages;
622
623    final int mSdkVersion = Build.VERSION.SDK_INT;
624
625    final Context mContext;
626    final boolean mFactoryTest;
627    final boolean mOnlyCore;
628    final DisplayMetrics mMetrics;
629    final int mDefParseFlags;
630    final String[] mSeparateProcesses;
631    final boolean mIsUpgrade;
632    final boolean mIsPreNUpgrade;
633    final boolean mIsPreNMR1Upgrade;
634
635    // Have we told the Activity Manager to whitelist the default container service by uid yet?
636    @GuardedBy("mPackages")
637    boolean mDefaultContainerWhitelisted = false;
638
639    @GuardedBy("mPackages")
640    private boolean mDexOptDialogShown;
641
642    /** The location for ASEC container files on internal storage. */
643    final String mAsecInternalPath;
644
645    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
646    // LOCK HELD.  Can be called with mInstallLock held.
647    @GuardedBy("mInstallLock")
648    final Installer mInstaller;
649
650    /** Directory where installed third-party apps stored */
651    final File mAppInstallDir;
652
653    /**
654     * Directory to which applications installed internally have their
655     * 32 bit native libraries copied.
656     */
657    private File mAppLib32InstallDir;
658
659    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
660    // apps.
661    final File mDrmAppPrivateInstallDir;
662
663    // ----------------------------------------------------------------
664
665    // Lock for state used when installing and doing other long running
666    // operations.  Methods that must be called with this lock held have
667    // the suffix "LI".
668    final Object mInstallLock = new Object();
669
670    // ----------------------------------------------------------------
671
672    // Keys are String (package name), values are Package.  This also serves
673    // as the lock for the global state.  Methods that must be called with
674    // this lock held have the prefix "LP".
675    @GuardedBy("mPackages")
676    final ArrayMap<String, PackageParser.Package> mPackages =
677            new ArrayMap<String, PackageParser.Package>();
678
679    final ArrayMap<String, Set<String>> mKnownCodebase =
680            new ArrayMap<String, Set<String>>();
681
682    // Keys are isolated uids and values are the uid of the application
683    // that created the isolated proccess.
684    @GuardedBy("mPackages")
685    final SparseIntArray mIsolatedOwners = new SparseIntArray();
686
687    /**
688     * Tracks new system packages [received in an OTA] that we expect to
689     * find updated user-installed versions. Keys are package name, values
690     * are package location.
691     */
692    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
693    /**
694     * Tracks high priority intent filters for protected actions. During boot, certain
695     * filter actions are protected and should never be allowed to have a high priority
696     * intent filter for them. However, there is one, and only one exception -- the
697     * setup wizard. It must be able to define a high priority intent filter for these
698     * actions to ensure there are no escapes from the wizard. We need to delay processing
699     * of these during boot as we need to look at all of the system packages in order
700     * to know which component is the setup wizard.
701     */
702    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
703    /**
704     * Whether or not processing protected filters should be deferred.
705     */
706    private boolean mDeferProtectedFilters = true;
707
708    /**
709     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
710     */
711    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
712    /**
713     * Whether or not system app permissions should be promoted from install to runtime.
714     */
715    boolean mPromoteSystemApps;
716
717    @GuardedBy("mPackages")
718    final Settings mSettings;
719
720    /**
721     * Set of package names that are currently "frozen", which means active
722     * surgery is being done on the code/data for that package. The platform
723     * will refuse to launch frozen packages to avoid race conditions.
724     *
725     * @see PackageFreezer
726     */
727    @GuardedBy("mPackages")
728    final ArraySet<String> mFrozenPackages = new ArraySet<>();
729
730    final ProtectedPackages mProtectedPackages;
731
732    boolean mFirstBoot;
733
734    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
735
736    // System configuration read by SystemConfig.
737    final int[] mGlobalGids;
738    final SparseArray<ArraySet<String>> mSystemPermissions;
739    @GuardedBy("mAvailableFeatures")
740    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
741
742    // If mac_permissions.xml was found for seinfo labeling.
743    boolean mFoundPolicyFile;
744
745    private final InstantAppRegistry mInstantAppRegistry;
746
747    @GuardedBy("mPackages")
748    int mChangedPackagesSequenceNumber;
749    /**
750     * List of changed [installed, removed or updated] packages.
751     * mapping from user id -> sequence number -> package name
752     */
753    @GuardedBy("mPackages")
754    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
755    /**
756     * The sequence number of the last change to a package.
757     * mapping from user id -> package name -> sequence number
758     */
759    @GuardedBy("mPackages")
760    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
761
762    class PackageParserCallback implements PackageParser.Callback {
763        @Override public final boolean hasFeature(String feature) {
764            return PackageManagerService.this.hasSystemFeature(feature, 0);
765        }
766
767        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
768                Collection<PackageParser.Package> allPackages, String targetPackageName) {
769            List<PackageParser.Package> overlayPackages = null;
770            for (PackageParser.Package p : allPackages) {
771                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
772                    if (overlayPackages == null) {
773                        overlayPackages = new ArrayList<PackageParser.Package>();
774                    }
775                    overlayPackages.add(p);
776                }
777            }
778            if (overlayPackages != null) {
779                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
780                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
781                        return p1.mOverlayPriority - p2.mOverlayPriority;
782                    }
783                };
784                Collections.sort(overlayPackages, cmp);
785            }
786            return overlayPackages;
787        }
788
789        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
790                String targetPackageName, String targetPath) {
791            if ("android".equals(targetPackageName)) {
792                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
793                // native AssetManager.
794                return null;
795            }
796            List<PackageParser.Package> overlayPackages =
797                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
798            if (overlayPackages == null || overlayPackages.isEmpty()) {
799                return null;
800            }
801            List<String> overlayPathList = null;
802            for (PackageParser.Package overlayPackage : overlayPackages) {
803                if (targetPath == null) {
804                    if (overlayPathList == null) {
805                        overlayPathList = new ArrayList<String>();
806                    }
807                    overlayPathList.add(overlayPackage.baseCodePath);
808                    continue;
809                }
810
811                try {
812                    // Creates idmaps for system to parse correctly the Android manifest of the
813                    // target package.
814                    //
815                    // OverlayManagerService will update each of them with a correct gid from its
816                    // target package app id.
817                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
818                            UserHandle.getSharedAppGid(
819                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
820                    if (overlayPathList == null) {
821                        overlayPathList = new ArrayList<String>();
822                    }
823                    overlayPathList.add(overlayPackage.baseCodePath);
824                } catch (InstallerException e) {
825                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
826                            overlayPackage.baseCodePath);
827                }
828            }
829            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
830        }
831
832        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
833            synchronized (mPackages) {
834                return getStaticOverlayPathsLocked(
835                        mPackages.values(), targetPackageName, targetPath);
836            }
837        }
838
839        @Override public final String[] getOverlayApks(String targetPackageName) {
840            return getStaticOverlayPaths(targetPackageName, null);
841        }
842
843        @Override public final String[] getOverlayPaths(String targetPackageName,
844                String targetPath) {
845            return getStaticOverlayPaths(targetPackageName, targetPath);
846        }
847    };
848
849    class ParallelPackageParserCallback extends PackageParserCallback {
850        List<PackageParser.Package> mOverlayPackages = null;
851
852        void findStaticOverlayPackages() {
853            synchronized (mPackages) {
854                for (PackageParser.Package p : mPackages.values()) {
855                    if (p.mIsStaticOverlay) {
856                        if (mOverlayPackages == null) {
857                            mOverlayPackages = new ArrayList<PackageParser.Package>();
858                        }
859                        mOverlayPackages.add(p);
860                    }
861                }
862            }
863        }
864
865        @Override
866        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
867            // We can trust mOverlayPackages without holding mPackages because package uninstall
868            // can't happen while running parallel parsing.
869            // Moreover holding mPackages on each parsing thread causes dead-lock.
870            return mOverlayPackages == null ? null :
871                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
872        }
873    }
874
875    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
876    final ParallelPackageParserCallback mParallelPackageParserCallback =
877            new ParallelPackageParserCallback();
878
879    public static final class SharedLibraryEntry {
880        public final @Nullable String path;
881        public final @Nullable String apk;
882        public final @NonNull SharedLibraryInfo info;
883
884        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
885                String declaringPackageName, int declaringPackageVersionCode) {
886            path = _path;
887            apk = _apk;
888            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
889                    declaringPackageName, declaringPackageVersionCode), null);
890        }
891    }
892
893    // Currently known shared libraries.
894    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
895    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
896            new ArrayMap<>();
897
898    // All available activities, for your resolving pleasure.
899    final ActivityIntentResolver mActivities =
900            new ActivityIntentResolver();
901
902    // All available receivers, for your resolving pleasure.
903    final ActivityIntentResolver mReceivers =
904            new ActivityIntentResolver();
905
906    // All available services, for your resolving pleasure.
907    final ServiceIntentResolver mServices = new ServiceIntentResolver();
908
909    // All available providers, for your resolving pleasure.
910    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
911
912    // Mapping from provider base names (first directory in content URI codePath)
913    // to the provider information.
914    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
915            new ArrayMap<String, PackageParser.Provider>();
916
917    // Mapping from instrumentation class names to info about them.
918    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
919            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
920
921    // Mapping from permission names to info about them.
922    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
923            new ArrayMap<String, PackageParser.PermissionGroup>();
924
925    // Packages whose data we have transfered into another package, thus
926    // should no longer exist.
927    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
928
929    // Broadcast actions that are only available to the system.
930    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
931
932    /** List of packages waiting for verification. */
933    final SparseArray<PackageVerificationState> mPendingVerification
934            = new SparseArray<PackageVerificationState>();
935
936    /** Set of packages associated with each app op permission. */
937    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
938
939    final PackageInstallerService mInstallerService;
940
941    private final PackageDexOptimizer mPackageDexOptimizer;
942    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
943    // is used by other apps).
944    private final DexManager mDexManager;
945
946    private AtomicInteger mNextMoveId = new AtomicInteger();
947    private final MoveCallbacks mMoveCallbacks;
948
949    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
950
951    // Cache of users who need badging.
952    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
953
954    /** Token for keys in mPendingVerification. */
955    private int mPendingVerificationToken = 0;
956
957    volatile boolean mSystemReady;
958    volatile boolean mSafeMode;
959    volatile boolean mHasSystemUidErrors;
960    private volatile boolean mEphemeralAppsDisabled;
961
962    ApplicationInfo mAndroidApplication;
963    final ActivityInfo mResolveActivity = new ActivityInfo();
964    final ResolveInfo mResolveInfo = new ResolveInfo();
965    ComponentName mResolveComponentName;
966    PackageParser.Package mPlatformPackage;
967    ComponentName mCustomResolverComponentName;
968
969    boolean mResolverReplaced = false;
970
971    private final @Nullable ComponentName mIntentFilterVerifierComponent;
972    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
973
974    private int mIntentFilterVerificationToken = 0;
975
976    /** The service connection to the ephemeral resolver */
977    final EphemeralResolverConnection mInstantAppResolverConnection;
978    /** Component used to show resolver settings for Instant Apps */
979    final ComponentName mInstantAppResolverSettingsComponent;
980
981    /** Activity used to install instant applications */
982    ActivityInfo mInstantAppInstallerActivity;
983    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
984
985    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
986            = new SparseArray<IntentFilterVerificationState>();
987
988    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
989
990    // List of packages names to keep cached, even if they are uninstalled for all users
991    private List<String> mKeepUninstalledPackages;
992
993    private UserManagerInternal mUserManagerInternal;
994
995    private DeviceIdleController.LocalService mDeviceIdleController;
996
997    private File mCacheDir;
998
999    private ArraySet<String> mPrivappPermissionsViolations;
1000
1001    private Future<?> mPrepareAppDataFuture;
1002
1003    private static class IFVerificationParams {
1004        PackageParser.Package pkg;
1005        boolean replacing;
1006        int userId;
1007        int verifierUid;
1008
1009        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1010                int _userId, int _verifierUid) {
1011            pkg = _pkg;
1012            replacing = _replacing;
1013            userId = _userId;
1014            replacing = _replacing;
1015            verifierUid = _verifierUid;
1016        }
1017    }
1018
1019    private interface IntentFilterVerifier<T extends IntentFilter> {
1020        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1021                                               T filter, String packageName);
1022        void startVerifications(int userId);
1023        void receiveVerificationResponse(int verificationId);
1024    }
1025
1026    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1027        private Context mContext;
1028        private ComponentName mIntentFilterVerifierComponent;
1029        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1030
1031        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1032            mContext = context;
1033            mIntentFilterVerifierComponent = verifierComponent;
1034        }
1035
1036        private String getDefaultScheme() {
1037            return IntentFilter.SCHEME_HTTPS;
1038        }
1039
1040        @Override
1041        public void startVerifications(int userId) {
1042            // Launch verifications requests
1043            int count = mCurrentIntentFilterVerifications.size();
1044            for (int n=0; n<count; n++) {
1045                int verificationId = mCurrentIntentFilterVerifications.get(n);
1046                final IntentFilterVerificationState ivs =
1047                        mIntentFilterVerificationStates.get(verificationId);
1048
1049                String packageName = ivs.getPackageName();
1050
1051                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1052                final int filterCount = filters.size();
1053                ArraySet<String> domainsSet = new ArraySet<>();
1054                for (int m=0; m<filterCount; m++) {
1055                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1056                    domainsSet.addAll(filter.getHostsList());
1057                }
1058                synchronized (mPackages) {
1059                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1060                            packageName, domainsSet) != null) {
1061                        scheduleWriteSettingsLocked();
1062                    }
1063                }
1064                sendVerificationRequest(userId, verificationId, ivs);
1065            }
1066            mCurrentIntentFilterVerifications.clear();
1067        }
1068
1069        private void sendVerificationRequest(int userId, int verificationId,
1070                IntentFilterVerificationState ivs) {
1071
1072            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1075                    verificationId);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1078                    getDefaultScheme());
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1081                    ivs.getHostsString());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1084                    ivs.getPackageName());
1085            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1086            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1087
1088            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1089            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1090                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1091                    userId, false, "intent filter verifier");
1092
1093            UserHandle user = new UserHandle(userId);
1094            mContext.sendBroadcastAsUser(verificationIntent, user);
1095            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1096                    "Sending IntentFilter verification broadcast");
1097        }
1098
1099        public void receiveVerificationResponse(int verificationId) {
1100            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1101
1102            final boolean verified = ivs.isVerified();
1103
1104            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1105            final int count = filters.size();
1106            if (DEBUG_DOMAIN_VERIFICATION) {
1107                Slog.i(TAG, "Received verification response " + verificationId
1108                        + " for " + count + " filters, verified=" + verified);
1109            }
1110            for (int n=0; n<count; n++) {
1111                PackageParser.ActivityIntentInfo filter = filters.get(n);
1112                filter.setVerified(verified);
1113
1114                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1115                        + " verified with result:" + verified + " and hosts:"
1116                        + ivs.getHostsString());
1117            }
1118
1119            mIntentFilterVerificationStates.remove(verificationId);
1120
1121            final String packageName = ivs.getPackageName();
1122            IntentFilterVerificationInfo ivi = null;
1123
1124            synchronized (mPackages) {
1125                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1126            }
1127            if (ivi == null) {
1128                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1129                        + verificationId + " packageName:" + packageName);
1130                return;
1131            }
1132            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1133                    "Updating IntentFilterVerificationInfo for package " + packageName
1134                            +" verificationId:" + verificationId);
1135
1136            synchronized (mPackages) {
1137                if (verified) {
1138                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1139                } else {
1140                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1141                }
1142                scheduleWriteSettingsLocked();
1143
1144                final int userId = ivs.getUserId();
1145                if (userId != UserHandle.USER_ALL) {
1146                    final int userStatus =
1147                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1148
1149                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1150                    boolean needUpdate = false;
1151
1152                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1153                    // already been set by the User thru the Disambiguation dialog
1154                    switch (userStatus) {
1155                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1156                            if (verified) {
1157                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1158                            } else {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1160                            }
1161                            needUpdate = true;
1162                            break;
1163
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                                needUpdate = true;
1168                            }
1169                            break;
1170
1171                        default:
1172                            // Nothing to do
1173                    }
1174
1175                    if (needUpdate) {
1176                        mSettings.updateIntentFilterVerificationStatusLPw(
1177                                packageName, updatedStatus, userId);
1178                        scheduleWritePackageRestrictionsLocked(userId);
1179                    }
1180                }
1181            }
1182        }
1183
1184        @Override
1185        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1186                    ActivityIntentInfo filter, String packageName) {
1187            if (!hasValidDomains(filter)) {
1188                return false;
1189            }
1190            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1191            if (ivs == null) {
1192                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1193                        packageName);
1194            }
1195            if (DEBUG_DOMAIN_VERIFICATION) {
1196                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1197            }
1198            ivs.addFilter(filter);
1199            return true;
1200        }
1201
1202        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1203                int userId, int verificationId, String packageName) {
1204            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1205                    verifierUid, userId, packageName);
1206            ivs.setPendingState();
1207            synchronized (mPackages) {
1208                mIntentFilterVerificationStates.append(verificationId, ivs);
1209                mCurrentIntentFilterVerifications.add(verificationId);
1210            }
1211            return ivs;
1212        }
1213    }
1214
1215    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1216        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1217                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1218                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1219    }
1220
1221    // Set of pending broadcasts for aggregating enable/disable of components.
1222    static class PendingPackageBroadcasts {
1223        // for each user id, a map of <package name -> components within that package>
1224        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1225
1226        public PendingPackageBroadcasts() {
1227            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1228        }
1229
1230        public ArrayList<String> get(int userId, String packageName) {
1231            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1232            return packages.get(packageName);
1233        }
1234
1235        public void put(int userId, String packageName, ArrayList<String> components) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            packages.put(packageName, components);
1238        }
1239
1240        public void remove(int userId, String packageName) {
1241            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1242            if (packages != null) {
1243                packages.remove(packageName);
1244            }
1245        }
1246
1247        public void remove(int userId) {
1248            mUidMap.remove(userId);
1249        }
1250
1251        public int userIdCount() {
1252            return mUidMap.size();
1253        }
1254
1255        public int userIdAt(int n) {
1256            return mUidMap.keyAt(n);
1257        }
1258
1259        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1260            return mUidMap.get(userId);
1261        }
1262
1263        public int size() {
1264            // total number of pending broadcast entries across all userIds
1265            int num = 0;
1266            for (int i = 0; i< mUidMap.size(); i++) {
1267                num += mUidMap.valueAt(i).size();
1268            }
1269            return num;
1270        }
1271
1272        public void clear() {
1273            mUidMap.clear();
1274        }
1275
1276        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1277            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1278            if (map == null) {
1279                map = new ArrayMap<String, ArrayList<String>>();
1280                mUidMap.put(userId, map);
1281            }
1282            return map;
1283        }
1284    }
1285    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1286
1287    // Service Connection to remote media container service to copy
1288    // package uri's from external media onto secure containers
1289    // or internal storage.
1290    private IMediaContainerService mContainerService = null;
1291
1292    static final int SEND_PENDING_BROADCAST = 1;
1293    static final int MCS_BOUND = 3;
1294    static final int END_COPY = 4;
1295    static final int INIT_COPY = 5;
1296    static final int MCS_UNBIND = 6;
1297    static final int START_CLEANING_PACKAGE = 7;
1298    static final int FIND_INSTALL_LOC = 8;
1299    static final int POST_INSTALL = 9;
1300    static final int MCS_RECONNECT = 10;
1301    static final int MCS_GIVE_UP = 11;
1302    static final int UPDATED_MEDIA_STATUS = 12;
1303    static final int WRITE_SETTINGS = 13;
1304    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1305    static final int PACKAGE_VERIFIED = 15;
1306    static final int CHECK_PENDING_VERIFICATION = 16;
1307    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1308    static final int INTENT_FILTER_VERIFIED = 18;
1309    static final int WRITE_PACKAGE_LIST = 19;
1310    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1311
1312    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1313
1314    // Delay time in millisecs
1315    static final int BROADCAST_DELAY = 10 * 1000;
1316
1317    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1318            2 * 60 * 60 * 1000L; /* two hours */
1319
1320    static UserManagerService sUserManager;
1321
1322    // Stores a list of users whose package restrictions file needs to be updated
1323    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1324
1325    final private DefaultContainerConnection mDefContainerConn =
1326            new DefaultContainerConnection();
1327    class DefaultContainerConnection implements ServiceConnection {
1328        public void onServiceConnected(ComponentName name, IBinder service) {
1329            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1330            final IMediaContainerService imcs = IMediaContainerService.Stub
1331                    .asInterface(Binder.allowBlocking(service));
1332            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1333        }
1334
1335        public void onServiceDisconnected(ComponentName name) {
1336            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1337        }
1338    }
1339
1340    // Recordkeeping of restore-after-install operations that are currently in flight
1341    // between the Package Manager and the Backup Manager
1342    static class PostInstallData {
1343        public InstallArgs args;
1344        public PackageInstalledInfo res;
1345
1346        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1347            args = _a;
1348            res = _r;
1349        }
1350    }
1351
1352    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1353    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1354
1355    // XML tags for backup/restore of various bits of state
1356    private static final String TAG_PREFERRED_BACKUP = "pa";
1357    private static final String TAG_DEFAULT_APPS = "da";
1358    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1359
1360    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1361    private static final String TAG_ALL_GRANTS = "rt-grants";
1362    private static final String TAG_GRANT = "grant";
1363    private static final String ATTR_PACKAGE_NAME = "pkg";
1364
1365    private static final String TAG_PERMISSION = "perm";
1366    private static final String ATTR_PERMISSION_NAME = "name";
1367    private static final String ATTR_IS_GRANTED = "g";
1368    private static final String ATTR_USER_SET = "set";
1369    private static final String ATTR_USER_FIXED = "fixed";
1370    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1371
1372    // System/policy permission grants are not backed up
1373    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1374            FLAG_PERMISSION_POLICY_FIXED
1375            | FLAG_PERMISSION_SYSTEM_FIXED
1376            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1377
1378    // And we back up these user-adjusted states
1379    private static final int USER_RUNTIME_GRANT_MASK =
1380            FLAG_PERMISSION_USER_SET
1381            | FLAG_PERMISSION_USER_FIXED
1382            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1383
1384    final @Nullable String mRequiredVerifierPackage;
1385    final @NonNull String mRequiredInstallerPackage;
1386    final @NonNull String mRequiredUninstallerPackage;
1387    final @Nullable String mSetupWizardPackage;
1388    final @Nullable String mStorageManagerPackage;
1389    final @NonNull String mServicesSystemSharedLibraryPackageName;
1390    final @NonNull String mSharedSystemSharedLibraryPackageName;
1391
1392    final boolean mPermissionReviewRequired;
1393
1394    private final PackageUsage mPackageUsage = new PackageUsage();
1395    private final CompilerStats mCompilerStats = new CompilerStats();
1396
1397    class PackageHandler extends Handler {
1398        private boolean mBound = false;
1399        final ArrayList<HandlerParams> mPendingInstalls =
1400            new ArrayList<HandlerParams>();
1401
1402        private boolean connectToService() {
1403            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1404                    " DefaultContainerService");
1405            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1406            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1407            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1408                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1409                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                mBound = true;
1411                return true;
1412            }
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414            return false;
1415        }
1416
1417        private void disconnectService() {
1418            mContainerService = null;
1419            mBound = false;
1420            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1421            mContext.unbindService(mDefContainerConn);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423        }
1424
1425        PackageHandler(Looper looper) {
1426            super(looper);
1427        }
1428
1429        public void handleMessage(Message msg) {
1430            try {
1431                doHandleMessage(msg);
1432            } finally {
1433                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1434            }
1435        }
1436
1437        void doHandleMessage(Message msg) {
1438            switch (msg.what) {
1439                case INIT_COPY: {
1440                    HandlerParams params = (HandlerParams) msg.obj;
1441                    int idx = mPendingInstalls.size();
1442                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1443                    // If a bind was already initiated we dont really
1444                    // need to do anything. The pending install
1445                    // will be processed later on.
1446                    if (!mBound) {
1447                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1448                                System.identityHashCode(mHandler));
1449                        // If this is the only one pending we might
1450                        // have to bind to the service again.
1451                        if (!connectToService()) {
1452                            Slog.e(TAG, "Failed to bind to media container service");
1453                            params.serviceError();
1454                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1455                                    System.identityHashCode(mHandler));
1456                            if (params.traceMethod != null) {
1457                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1458                                        params.traceCookie);
1459                            }
1460                            return;
1461                        } else {
1462                            // Once we bind to the service, the first
1463                            // pending request will be processed.
1464                            mPendingInstalls.add(idx, params);
1465                        }
1466                    } else {
1467                        mPendingInstalls.add(idx, params);
1468                        // Already bound to the service. Just make
1469                        // sure we trigger off processing the first request.
1470                        if (idx == 0) {
1471                            mHandler.sendEmptyMessage(MCS_BOUND);
1472                        }
1473                    }
1474                    break;
1475                }
1476                case MCS_BOUND: {
1477                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1478                    if (msg.obj != null) {
1479                        mContainerService = (IMediaContainerService) msg.obj;
1480                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1481                                System.identityHashCode(mHandler));
1482                    }
1483                    if (mContainerService == null) {
1484                        if (!mBound) {
1485                            // Something seriously wrong since we are not bound and we are not
1486                            // waiting for connection. Bail out.
1487                            Slog.e(TAG, "Cannot bind to media container service");
1488                            for (HandlerParams params : mPendingInstalls) {
1489                                // Indicate service bind error
1490                                params.serviceError();
1491                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1492                                        System.identityHashCode(params));
1493                                if (params.traceMethod != null) {
1494                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1495                                            params.traceMethod, params.traceCookie);
1496                                }
1497                                return;
1498                            }
1499                            mPendingInstalls.clear();
1500                        } else {
1501                            Slog.w(TAG, "Waiting to connect to media container service");
1502                        }
1503                    } else if (mPendingInstalls.size() > 0) {
1504                        HandlerParams params = mPendingInstalls.get(0);
1505                        if (params != null) {
1506                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1507                                    System.identityHashCode(params));
1508                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1509                            if (params.startCopy()) {
1510                                // We are done...  look for more work or to
1511                                // go idle.
1512                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1513                                        "Checking for more work or unbind...");
1514                                // Delete pending install
1515                                if (mPendingInstalls.size() > 0) {
1516                                    mPendingInstalls.remove(0);
1517                                }
1518                                if (mPendingInstalls.size() == 0) {
1519                                    if (mBound) {
1520                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1521                                                "Posting delayed MCS_UNBIND");
1522                                        removeMessages(MCS_UNBIND);
1523                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1524                                        // Unbind after a little delay, to avoid
1525                                        // continual thrashing.
1526                                        sendMessageDelayed(ubmsg, 10000);
1527                                    }
1528                                } else {
1529                                    // There are more pending requests in queue.
1530                                    // Just post MCS_BOUND message to trigger processing
1531                                    // of next pending install.
1532                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1533                                            "Posting MCS_BOUND for next work");
1534                                    mHandler.sendEmptyMessage(MCS_BOUND);
1535                                }
1536                            }
1537                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1538                        }
1539                    } else {
1540                        // Should never happen ideally.
1541                        Slog.w(TAG, "Empty queue");
1542                    }
1543                    break;
1544                }
1545                case MCS_RECONNECT: {
1546                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1547                    if (mPendingInstalls.size() > 0) {
1548                        if (mBound) {
1549                            disconnectService();
1550                        }
1551                        if (!connectToService()) {
1552                            Slog.e(TAG, "Failed to bind to media container service");
1553                            for (HandlerParams params : mPendingInstalls) {
1554                                // Indicate service bind error
1555                                params.serviceError();
1556                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1557                                        System.identityHashCode(params));
1558                            }
1559                            mPendingInstalls.clear();
1560                        }
1561                    }
1562                    break;
1563                }
1564                case MCS_UNBIND: {
1565                    // If there is no actual work left, then time to unbind.
1566                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1567
1568                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1569                        if (mBound) {
1570                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1571
1572                            disconnectService();
1573                        }
1574                    } else if (mPendingInstalls.size() > 0) {
1575                        // There are more pending requests in queue.
1576                        // Just post MCS_BOUND message to trigger processing
1577                        // of next pending install.
1578                        mHandler.sendEmptyMessage(MCS_BOUND);
1579                    }
1580
1581                    break;
1582                }
1583                case MCS_GIVE_UP: {
1584                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1585                    HandlerParams params = mPendingInstalls.remove(0);
1586                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1587                            System.identityHashCode(params));
1588                    break;
1589                }
1590                case SEND_PENDING_BROADCAST: {
1591                    String packages[];
1592                    ArrayList<String> components[];
1593                    int size = 0;
1594                    int uids[];
1595                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1596                    synchronized (mPackages) {
1597                        if (mPendingBroadcasts == null) {
1598                            return;
1599                        }
1600                        size = mPendingBroadcasts.size();
1601                        if (size <= 0) {
1602                            // Nothing to be done. Just return
1603                            return;
1604                        }
1605                        packages = new String[size];
1606                        components = new ArrayList[size];
1607                        uids = new int[size];
1608                        int i = 0;  // filling out the above arrays
1609
1610                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1611                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1612                            Iterator<Map.Entry<String, ArrayList<String>>> it
1613                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1614                                            .entrySet().iterator();
1615                            while (it.hasNext() && i < size) {
1616                                Map.Entry<String, ArrayList<String>> ent = it.next();
1617                                packages[i] = ent.getKey();
1618                                components[i] = ent.getValue();
1619                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1620                                uids[i] = (ps != null)
1621                                        ? UserHandle.getUid(packageUserId, ps.appId)
1622                                        : -1;
1623                                i++;
1624                            }
1625                        }
1626                        size = i;
1627                        mPendingBroadcasts.clear();
1628                    }
1629                    // Send broadcasts
1630                    for (int i = 0; i < size; i++) {
1631                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1632                    }
1633                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1634                    break;
1635                }
1636                case START_CLEANING_PACKAGE: {
1637                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1638                    final String packageName = (String)msg.obj;
1639                    final int userId = msg.arg1;
1640                    final boolean andCode = msg.arg2 != 0;
1641                    synchronized (mPackages) {
1642                        if (userId == UserHandle.USER_ALL) {
1643                            int[] users = sUserManager.getUserIds();
1644                            for (int user : users) {
1645                                mSettings.addPackageToCleanLPw(
1646                                        new PackageCleanItem(user, packageName, andCode));
1647                            }
1648                        } else {
1649                            mSettings.addPackageToCleanLPw(
1650                                    new PackageCleanItem(userId, packageName, andCode));
1651                        }
1652                    }
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1654                    startCleaningPackages();
1655                } break;
1656                case POST_INSTALL: {
1657                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1658
1659                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1660                    final boolean didRestore = (msg.arg2 != 0);
1661                    mRunningInstalls.delete(msg.arg1);
1662
1663                    if (data != null) {
1664                        InstallArgs args = data.args;
1665                        PackageInstalledInfo parentRes = data.res;
1666
1667                        final boolean grantPermissions = (args.installFlags
1668                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1669                        final boolean killApp = (args.installFlags
1670                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1671                        final String[] grantedPermissions = args.installGrantPermissions;
1672
1673                        // Handle the parent package
1674                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1675                                grantedPermissions, didRestore, args.installerPackageName,
1676                                args.observer);
1677
1678                        // Handle the child packages
1679                        final int childCount = (parentRes.addedChildPackages != null)
1680                                ? parentRes.addedChildPackages.size() : 0;
1681                        for (int i = 0; i < childCount; i++) {
1682                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1683                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1684                                    grantedPermissions, false, args.installerPackageName,
1685                                    args.observer);
1686                        }
1687
1688                        // Log tracing if needed
1689                        if (args.traceMethod != null) {
1690                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1691                                    args.traceCookie);
1692                        }
1693                    } else {
1694                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1695                    }
1696
1697                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1698                } break;
1699                case UPDATED_MEDIA_STATUS: {
1700                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1701                    boolean reportStatus = msg.arg1 == 1;
1702                    boolean doGc = msg.arg2 == 1;
1703                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1704                    if (doGc) {
1705                        // Force a gc to clear up stale containers.
1706                        Runtime.getRuntime().gc();
1707                    }
1708                    if (msg.obj != null) {
1709                        @SuppressWarnings("unchecked")
1710                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1711                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1712                        // Unload containers
1713                        unloadAllContainers(args);
1714                    }
1715                    if (reportStatus) {
1716                        try {
1717                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1718                                    "Invoking StorageManagerService call back");
1719                            PackageHelper.getStorageManager().finishMediaUpdate();
1720                        } catch (RemoteException e) {
1721                            Log.e(TAG, "StorageManagerService not running?");
1722                        }
1723                    }
1724                } break;
1725                case WRITE_SETTINGS: {
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1727                    synchronized (mPackages) {
1728                        removeMessages(WRITE_SETTINGS);
1729                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1730                        mSettings.writeLPr();
1731                        mDirtyUsers.clear();
1732                    }
1733                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1734                } break;
1735                case WRITE_PACKAGE_RESTRICTIONS: {
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1737                    synchronized (mPackages) {
1738                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1739                        for (int userId : mDirtyUsers) {
1740                            mSettings.writePackageRestrictionsLPr(userId);
1741                        }
1742                        mDirtyUsers.clear();
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case WRITE_PACKAGE_LIST: {
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1748                    synchronized (mPackages) {
1749                        removeMessages(WRITE_PACKAGE_LIST);
1750                        mSettings.writePackageListLPr(msg.arg1);
1751                    }
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1753                } break;
1754                case CHECK_PENDING_VERIFICATION: {
1755                    final int verificationId = msg.arg1;
1756                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1757
1758                    if ((state != null) && !state.timeoutExtended()) {
1759                        final InstallArgs args = state.getInstallArgs();
1760                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1761
1762                        Slog.i(TAG, "Verification timed out for " + originUri);
1763                        mPendingVerification.remove(verificationId);
1764
1765                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1766
1767                        final UserHandle user = args.getUser();
1768                        if (getDefaultVerificationResponse(user)
1769                                == PackageManager.VERIFICATION_ALLOW) {
1770                            Slog.i(TAG, "Continuing with installation of " + originUri);
1771                            state.setVerifierResponse(Binder.getCallingUid(),
1772                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1773                            broadcastPackageVerified(verificationId, originUri,
1774                                    PackageManager.VERIFICATION_ALLOW, user);
1775                            try {
1776                                ret = args.copyApk(mContainerService, true);
1777                            } catch (RemoteException e) {
1778                                Slog.e(TAG, "Could not contact the ContainerService");
1779                            }
1780                        } else {
1781                            broadcastPackageVerified(verificationId, originUri,
1782                                    PackageManager.VERIFICATION_REJECT, user);
1783                        }
1784
1785                        Trace.asyncTraceEnd(
1786                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1787
1788                        processPendingInstall(args, ret);
1789                        mHandler.sendEmptyMessage(MCS_UNBIND);
1790                    }
1791                    break;
1792                }
1793                case PACKAGE_VERIFIED: {
1794                    final int verificationId = msg.arg1;
1795
1796                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1797                    if (state == null) {
1798                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1799                        break;
1800                    }
1801
1802                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1803
1804                    state.setVerifierResponse(response.callerUid, response.code);
1805
1806                    if (state.isVerificationComplete()) {
1807                        mPendingVerification.remove(verificationId);
1808
1809                        final InstallArgs args = state.getInstallArgs();
1810                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1811
1812                        int ret;
1813                        if (state.isInstallAllowed()) {
1814                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1815                            broadcastPackageVerified(verificationId, originUri,
1816                                    response.code, state.getInstallArgs().getUser());
1817                            try {
1818                                ret = args.copyApk(mContainerService, true);
1819                            } catch (RemoteException e) {
1820                                Slog.e(TAG, "Could not contact the ContainerService");
1821                            }
1822                        } else {
1823                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1824                        }
1825
1826                        Trace.asyncTraceEnd(
1827                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1828
1829                        processPendingInstall(args, ret);
1830                        mHandler.sendEmptyMessage(MCS_UNBIND);
1831                    }
1832
1833                    break;
1834                }
1835                case START_INTENT_FILTER_VERIFICATIONS: {
1836                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1837                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1838                            params.replacing, params.pkg);
1839                    break;
1840                }
1841                case INTENT_FILTER_VERIFIED: {
1842                    final int verificationId = msg.arg1;
1843
1844                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1845                            verificationId);
1846                    if (state == null) {
1847                        Slog.w(TAG, "Invalid IntentFilter verification token "
1848                                + verificationId + " received");
1849                        break;
1850                    }
1851
1852                    final int userId = state.getUserId();
1853
1854                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1855                            "Processing IntentFilter verification with token:"
1856                            + verificationId + " and userId:" + userId);
1857
1858                    final IntentFilterVerificationResponse response =
1859                            (IntentFilterVerificationResponse) msg.obj;
1860
1861                    state.setVerifierResponse(response.callerUid, response.code);
1862
1863                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1864                            "IntentFilter verification with token:" + verificationId
1865                            + " and userId:" + userId
1866                            + " is settings verifier response with response code:"
1867                            + response.code);
1868
1869                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1870                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1871                                + response.getFailedDomainsString());
1872                    }
1873
1874                    if (state.isVerificationComplete()) {
1875                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1876                    } else {
1877                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1878                                "IntentFilter verification with token:" + verificationId
1879                                + " was not said to be complete");
1880                    }
1881
1882                    break;
1883                }
1884                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1885                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1886                            mInstantAppResolverConnection,
1887                            (InstantAppRequest) msg.obj,
1888                            mInstantAppInstallerActivity,
1889                            mHandler);
1890                }
1891            }
1892        }
1893    }
1894
1895    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1896            boolean killApp, String[] grantedPermissions,
1897            boolean launchedForRestore, String installerPackage,
1898            IPackageInstallObserver2 installObserver) {
1899        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1900            // Send the removed broadcasts
1901            if (res.removedInfo != null) {
1902                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1903            }
1904
1905            // Now that we successfully installed the package, grant runtime
1906            // permissions if requested before broadcasting the install. Also
1907            // for legacy apps in permission review mode we clear the permission
1908            // review flag which is used to emulate runtime permissions for
1909            // legacy apps.
1910            if (grantPermissions) {
1911                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1912            }
1913
1914            final boolean update = res.removedInfo != null
1915                    && res.removedInfo.removedPackage != null;
1916            final String origInstallerPackageName = res.removedInfo != null
1917                    ? res.removedInfo.installerPackageName : null;
1918
1919            // If this is the first time we have child packages for a disabled privileged
1920            // app that had no children, we grant requested runtime permissions to the new
1921            // children if the parent on the system image had them already granted.
1922            if (res.pkg.parentPackage != null) {
1923                synchronized (mPackages) {
1924                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1925                }
1926            }
1927
1928            synchronized (mPackages) {
1929                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1930            }
1931
1932            final String packageName = res.pkg.applicationInfo.packageName;
1933
1934            // Determine the set of users who are adding this package for
1935            // the first time vs. those who are seeing an update.
1936            int[] firstUsers = EMPTY_INT_ARRAY;
1937            int[] updateUsers = EMPTY_INT_ARRAY;
1938            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1939            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1940            for (int newUser : res.newUsers) {
1941                if (ps.getInstantApp(newUser)) {
1942                    continue;
1943                }
1944                if (allNewUsers) {
1945                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1946                    continue;
1947                }
1948                boolean isNew = true;
1949                for (int origUser : res.origUsers) {
1950                    if (origUser == newUser) {
1951                        isNew = false;
1952                        break;
1953                    }
1954                }
1955                if (isNew) {
1956                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1957                } else {
1958                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1959                }
1960            }
1961
1962            // Send installed broadcasts if the package is not a static shared lib.
1963            if (res.pkg.staticSharedLibName == null) {
1964                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1965
1966                // Send added for users that see the package for the first time
1967                // sendPackageAddedForNewUsers also deals with system apps
1968                int appId = UserHandle.getAppId(res.uid);
1969                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1970                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1971
1972                // Send added for users that don't see the package for the first time
1973                Bundle extras = new Bundle(1);
1974                extras.putInt(Intent.EXTRA_UID, res.uid);
1975                if (update) {
1976                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1977                }
1978                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1979                        extras, 0 /*flags*/,
1980                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1981                if (origInstallerPackageName != null) {
1982                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1983                            extras, 0 /*flags*/,
1984                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1985                }
1986
1987                // Send replaced for users that don't see the package for the first time
1988                if (update) {
1989                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1990                            packageName, extras, 0 /*flags*/,
1991                            null /*targetPackage*/, null /*finishedReceiver*/,
1992                            updateUsers);
1993                    if (origInstallerPackageName != null) {
1994                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1995                                extras, 0 /*flags*/,
1996                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1997                    }
1998                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1999                            null /*package*/, null /*extras*/, 0 /*flags*/,
2000                            packageName /*targetPackage*/,
2001                            null /*finishedReceiver*/, updateUsers);
2002                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2003                    // First-install and we did a restore, so we're responsible for the
2004                    // first-launch broadcast.
2005                    if (DEBUG_BACKUP) {
2006                        Slog.i(TAG, "Post-restore of " + packageName
2007                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2008                    }
2009                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2010                }
2011
2012                // Send broadcast package appeared if forward locked/external for all users
2013                // treat asec-hosted packages like removable media on upgrade
2014                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2015                    if (DEBUG_INSTALL) {
2016                        Slog.i(TAG, "upgrading pkg " + res.pkg
2017                                + " is ASEC-hosted -> AVAILABLE");
2018                    }
2019                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2020                    ArrayList<String> pkgList = new ArrayList<>(1);
2021                    pkgList.add(packageName);
2022                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2023                }
2024            }
2025
2026            // Work that needs to happen on first install within each user
2027            if (firstUsers != null && firstUsers.length > 0) {
2028                synchronized (mPackages) {
2029                    for (int userId : firstUsers) {
2030                        // If this app is a browser and it's newly-installed for some
2031                        // users, clear any default-browser state in those users. The
2032                        // app's nature doesn't depend on the user, so we can just check
2033                        // its browser nature in any user and generalize.
2034                        if (packageIsBrowser(packageName, userId)) {
2035                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2036                        }
2037
2038                        // We may also need to apply pending (restored) runtime
2039                        // permission grants within these users.
2040                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2041                    }
2042                }
2043            }
2044
2045            // Log current value of "unknown sources" setting
2046            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2047                    getUnknownSourcesSettings());
2048
2049            // Remove the replaced package's older resources safely now
2050            // We delete after a gc for applications  on sdcard.
2051            if (res.removedInfo != null && res.removedInfo.args != null) {
2052                Runtime.getRuntime().gc();
2053                synchronized (mInstallLock) {
2054                    res.removedInfo.args.doPostDeleteLI(true);
2055                }
2056            } else {
2057                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2058                // and not block here.
2059                VMRuntime.getRuntime().requestConcurrentGC();
2060            }
2061
2062            // Notify DexManager that the package was installed for new users.
2063            // The updated users should already be indexed and the package code paths
2064            // should not change.
2065            // Don't notify the manager for ephemeral apps as they are not expected to
2066            // survive long enough to benefit of background optimizations.
2067            for (int userId : firstUsers) {
2068                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2069                // There's a race currently where some install events may interleave with an uninstall.
2070                // This can lead to package info being null (b/36642664).
2071                if (info != null) {
2072                    mDexManager.notifyPackageInstalled(info, userId);
2073                }
2074            }
2075        }
2076
2077        // If someone is watching installs - notify them
2078        if (installObserver != null) {
2079            try {
2080                Bundle extras = extrasForInstallResult(res);
2081                installObserver.onPackageInstalled(res.name, res.returnCode,
2082                        res.returnMsg, extras);
2083            } catch (RemoteException e) {
2084                Slog.i(TAG, "Observer no longer exists.");
2085            }
2086        }
2087    }
2088
2089    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2090            PackageParser.Package pkg) {
2091        if (pkg.parentPackage == null) {
2092            return;
2093        }
2094        if (pkg.requestedPermissions == null) {
2095            return;
2096        }
2097        final PackageSetting disabledSysParentPs = mSettings
2098                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2099        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2100                || !disabledSysParentPs.isPrivileged()
2101                || (disabledSysParentPs.childPackageNames != null
2102                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2103            return;
2104        }
2105        final int[] allUserIds = sUserManager.getUserIds();
2106        final int permCount = pkg.requestedPermissions.size();
2107        for (int i = 0; i < permCount; i++) {
2108            String permission = pkg.requestedPermissions.get(i);
2109            BasePermission bp = mSettings.mPermissions.get(permission);
2110            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2111                continue;
2112            }
2113            for (int userId : allUserIds) {
2114                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2115                        permission, userId)) {
2116                    grantRuntimePermission(pkg.packageName, permission, userId);
2117                }
2118            }
2119        }
2120    }
2121
2122    private StorageEventListener mStorageListener = new StorageEventListener() {
2123        @Override
2124        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2125            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2126                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2127                    final String volumeUuid = vol.getFsUuid();
2128
2129                    // Clean up any users or apps that were removed or recreated
2130                    // while this volume was missing
2131                    sUserManager.reconcileUsers(volumeUuid);
2132                    reconcileApps(volumeUuid);
2133
2134                    // Clean up any install sessions that expired or were
2135                    // cancelled while this volume was missing
2136                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2137
2138                    loadPrivatePackages(vol);
2139
2140                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2141                    unloadPrivatePackages(vol);
2142                }
2143            }
2144
2145            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2146                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2147                    updateExternalMediaStatus(true, false);
2148                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2149                    updateExternalMediaStatus(false, false);
2150                }
2151            }
2152        }
2153
2154        @Override
2155        public void onVolumeForgotten(String fsUuid) {
2156            if (TextUtils.isEmpty(fsUuid)) {
2157                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2158                return;
2159            }
2160
2161            // Remove any apps installed on the forgotten volume
2162            synchronized (mPackages) {
2163                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2164                for (PackageSetting ps : packages) {
2165                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2166                    deletePackageVersioned(new VersionedPackage(ps.name,
2167                            PackageManager.VERSION_CODE_HIGHEST),
2168                            new LegacyPackageDeleteObserver(null).getBinder(),
2169                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2170                    // Try very hard to release any references to this package
2171                    // so we don't risk the system server being killed due to
2172                    // open FDs
2173                    AttributeCache.instance().removePackage(ps.name);
2174                }
2175
2176                mSettings.onVolumeForgotten(fsUuid);
2177                mSettings.writeLPr();
2178            }
2179        }
2180    };
2181
2182    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2183            String[] grantedPermissions) {
2184        for (int userId : userIds) {
2185            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2186        }
2187    }
2188
2189    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2190            String[] grantedPermissions) {
2191        PackageSetting ps = (PackageSetting) pkg.mExtras;
2192        if (ps == null) {
2193            return;
2194        }
2195
2196        PermissionsState permissionsState = ps.getPermissionsState();
2197
2198        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2199                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2200
2201        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2202                >= Build.VERSION_CODES.M;
2203
2204        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2205
2206        for (String permission : pkg.requestedPermissions) {
2207            final BasePermission bp;
2208            synchronized (mPackages) {
2209                bp = mSettings.mPermissions.get(permission);
2210            }
2211            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2212                    && (!instantApp || bp.isInstant())
2213                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2214                    && (grantedPermissions == null
2215                           || ArrayUtils.contains(grantedPermissions, permission))) {
2216                final int flags = permissionsState.getPermissionFlags(permission, userId);
2217                if (supportsRuntimePermissions) {
2218                    // Installer cannot change immutable permissions.
2219                    if ((flags & immutableFlags) == 0) {
2220                        grantRuntimePermission(pkg.packageName, permission, userId);
2221                    }
2222                } else if (mPermissionReviewRequired) {
2223                    // In permission review mode we clear the review flag when we
2224                    // are asked to install the app with all permissions granted.
2225                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2226                        updatePermissionFlags(permission, pkg.packageName,
2227                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2228                    }
2229                }
2230            }
2231        }
2232    }
2233
2234    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2235        Bundle extras = null;
2236        switch (res.returnCode) {
2237            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2238                extras = new Bundle();
2239                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2240                        res.origPermission);
2241                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2242                        res.origPackage);
2243                break;
2244            }
2245            case PackageManager.INSTALL_SUCCEEDED: {
2246                extras = new Bundle();
2247                extras.putBoolean(Intent.EXTRA_REPLACING,
2248                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2249                break;
2250            }
2251        }
2252        return extras;
2253    }
2254
2255    void scheduleWriteSettingsLocked() {
2256        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2257            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2258        }
2259    }
2260
2261    void scheduleWritePackageListLocked(int userId) {
2262        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2263            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2264            msg.arg1 = userId;
2265            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2266        }
2267    }
2268
2269    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2270        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2271        scheduleWritePackageRestrictionsLocked(userId);
2272    }
2273
2274    void scheduleWritePackageRestrictionsLocked(int userId) {
2275        final int[] userIds = (userId == UserHandle.USER_ALL)
2276                ? sUserManager.getUserIds() : new int[]{userId};
2277        for (int nextUserId : userIds) {
2278            if (!sUserManager.exists(nextUserId)) return;
2279            mDirtyUsers.add(nextUserId);
2280            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2281                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2282            }
2283        }
2284    }
2285
2286    public static PackageManagerService main(Context context, Installer installer,
2287            boolean factoryTest, boolean onlyCore) {
2288        // Self-check for initial settings.
2289        PackageManagerServiceCompilerMapping.checkProperties();
2290
2291        PackageManagerService m = new PackageManagerService(context, installer,
2292                factoryTest, onlyCore);
2293        m.enableSystemUserPackages();
2294        ServiceManager.addService("package", m);
2295        return m;
2296    }
2297
2298    private void enableSystemUserPackages() {
2299        if (!UserManager.isSplitSystemUser()) {
2300            return;
2301        }
2302        // For system user, enable apps based on the following conditions:
2303        // - app is whitelisted or belong to one of these groups:
2304        //   -- system app which has no launcher icons
2305        //   -- system app which has INTERACT_ACROSS_USERS permission
2306        //   -- system IME app
2307        // - app is not in the blacklist
2308        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2309        Set<String> enableApps = new ArraySet<>();
2310        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2311                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2312                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2313        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2314        enableApps.addAll(wlApps);
2315        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2316                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2317        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2318        enableApps.removeAll(blApps);
2319        Log.i(TAG, "Applications installed for system user: " + enableApps);
2320        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2321                UserHandle.SYSTEM);
2322        final int allAppsSize = allAps.size();
2323        synchronized (mPackages) {
2324            for (int i = 0; i < allAppsSize; i++) {
2325                String pName = allAps.get(i);
2326                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2327                // Should not happen, but we shouldn't be failing if it does
2328                if (pkgSetting == null) {
2329                    continue;
2330                }
2331                boolean install = enableApps.contains(pName);
2332                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2333                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2334                            + " for system user");
2335                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2336                }
2337            }
2338            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2339        }
2340    }
2341
2342    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2343        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2344                Context.DISPLAY_SERVICE);
2345        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2346    }
2347
2348    /**
2349     * Requests that files preopted on a secondary system partition be copied to the data partition
2350     * if possible.  Note that the actual copying of the files is accomplished by init for security
2351     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2352     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2353     */
2354    private static void requestCopyPreoptedFiles() {
2355        final int WAIT_TIME_MS = 100;
2356        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2357        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2358            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2359            // We will wait for up to 100 seconds.
2360            final long timeStart = SystemClock.uptimeMillis();
2361            final long timeEnd = timeStart + 100 * 1000;
2362            long timeNow = timeStart;
2363            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2364                try {
2365                    Thread.sleep(WAIT_TIME_MS);
2366                } catch (InterruptedException e) {
2367                    // Do nothing
2368                }
2369                timeNow = SystemClock.uptimeMillis();
2370                if (timeNow > timeEnd) {
2371                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2372                    Slog.wtf(TAG, "cppreopt did not finish!");
2373                    break;
2374                }
2375            }
2376
2377            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2378        }
2379    }
2380
2381    public PackageManagerService(Context context, Installer installer,
2382            boolean factoryTest, boolean onlyCore) {
2383        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2384        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2385        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2386                SystemClock.uptimeMillis());
2387
2388        if (mSdkVersion <= 0) {
2389            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2390        }
2391
2392        mContext = context;
2393
2394        mPermissionReviewRequired = context.getResources().getBoolean(
2395                R.bool.config_permissionReviewRequired);
2396
2397        mFactoryTest = factoryTest;
2398        mOnlyCore = onlyCore;
2399        mMetrics = new DisplayMetrics();
2400        mSettings = new Settings(mPackages);
2401        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413
2414        String separateProcesses = SystemProperties.get("debug.separate_processes");
2415        if (separateProcesses != null && separateProcesses.length() > 0) {
2416            if ("*".equals(separateProcesses)) {
2417                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2418                mSeparateProcesses = null;
2419                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2420            } else {
2421                mDefParseFlags = 0;
2422                mSeparateProcesses = separateProcesses.split(",");
2423                Slog.w(TAG, "Running with debug.separate_processes: "
2424                        + separateProcesses);
2425            }
2426        } else {
2427            mDefParseFlags = 0;
2428            mSeparateProcesses = null;
2429        }
2430
2431        mInstaller = installer;
2432        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2433                "*dexopt*");
2434        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2435        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2436
2437        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2438                FgThread.get().getLooper());
2439
2440        getDefaultDisplayMetrics(context, mMetrics);
2441
2442        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2443        SystemConfig systemConfig = SystemConfig.getInstance();
2444        mGlobalGids = systemConfig.getGlobalGids();
2445        mSystemPermissions = systemConfig.getSystemPermissions();
2446        mAvailableFeatures = systemConfig.getAvailableFeatures();
2447        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2448
2449        mProtectedPackages = new ProtectedPackages(mContext);
2450
2451        synchronized (mInstallLock) {
2452        // writer
2453        synchronized (mPackages) {
2454            mHandlerThread = new ServiceThread(TAG,
2455                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2456            mHandlerThread.start();
2457            mHandler = new PackageHandler(mHandlerThread.getLooper());
2458            mProcessLoggingHandler = new ProcessLoggingHandler();
2459            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2460
2461            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2462            mInstantAppRegistry = new InstantAppRegistry(this);
2463
2464            File dataDir = Environment.getDataDirectory();
2465            mAppInstallDir = new File(dataDir, "app");
2466            mAppLib32InstallDir = new File(dataDir, "app-lib");
2467            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2468            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2469            sUserManager = new UserManagerService(context, this,
2470                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2471
2472            // Propagate permission configuration in to package manager.
2473            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2474                    = systemConfig.getPermissions();
2475            for (int i=0; i<permConfig.size(); i++) {
2476                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2477                BasePermission bp = mSettings.mPermissions.get(perm.name);
2478                if (bp == null) {
2479                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2480                    mSettings.mPermissions.put(perm.name, bp);
2481                }
2482                if (perm.gids != null) {
2483                    bp.setGids(perm.gids, perm.perUser);
2484                }
2485            }
2486
2487            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2488            final int builtInLibCount = libConfig.size();
2489            for (int i = 0; i < builtInLibCount; i++) {
2490                String name = libConfig.keyAt(i);
2491                String path = libConfig.valueAt(i);
2492                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2493                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2494            }
2495
2496            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2497
2498            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2499            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2500            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2501
2502            // Clean up orphaned packages for which the code path doesn't exist
2503            // and they are an update to a system app - caused by bug/32321269
2504            final int packageSettingCount = mSettings.mPackages.size();
2505            for (int i = packageSettingCount - 1; i >= 0; i--) {
2506                PackageSetting ps = mSettings.mPackages.valueAt(i);
2507                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2508                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2509                    mSettings.mPackages.removeAt(i);
2510                    mSettings.enableSystemPackageLPw(ps.name);
2511                }
2512            }
2513
2514            if (mFirstBoot) {
2515                requestCopyPreoptedFiles();
2516            }
2517
2518            String customResolverActivity = Resources.getSystem().getString(
2519                    R.string.config_customResolverActivity);
2520            if (TextUtils.isEmpty(customResolverActivity)) {
2521                customResolverActivity = null;
2522            } else {
2523                mCustomResolverComponentName = ComponentName.unflattenFromString(
2524                        customResolverActivity);
2525            }
2526
2527            long startTime = SystemClock.uptimeMillis();
2528
2529            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2530                    startTime);
2531
2532            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2533            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2534
2535            if (bootClassPath == null) {
2536                Slog.w(TAG, "No BOOTCLASSPATH found!");
2537            }
2538
2539            if (systemServerClassPath == null) {
2540                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2541            }
2542
2543            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2544
2545            final VersionInfo ver = mSettings.getInternalVersion();
2546            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2547            if (mIsUpgrade) {
2548                logCriticalInfo(Log.INFO,
2549                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2550            }
2551
2552            // when upgrading from pre-M, promote system app permissions from install to runtime
2553            mPromoteSystemApps =
2554                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2555
2556            // When upgrading from pre-N, we need to handle package extraction like first boot,
2557            // as there is no profiling data available.
2558            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2559
2560            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2561
2562            // save off the names of pre-existing system packages prior to scanning; we don't
2563            // want to automatically grant runtime permissions for new system apps
2564            if (mPromoteSystemApps) {
2565                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2566                while (pkgSettingIter.hasNext()) {
2567                    PackageSetting ps = pkgSettingIter.next();
2568                    if (isSystemApp(ps)) {
2569                        mExistingSystemPackages.add(ps.name);
2570                    }
2571                }
2572            }
2573
2574            mCacheDir = preparePackageParserCache(mIsUpgrade);
2575
2576            // Set flag to monitor and not change apk file paths when
2577            // scanning install directories.
2578            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2579
2580            if (mIsUpgrade || mFirstBoot) {
2581                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2582            }
2583
2584            // Collect vendor overlay packages. (Do this before scanning any apps.)
2585            // For security and version matching reason, only consider
2586            // overlay packages if they reside in the right directory.
2587            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM
2589                    | PackageParser.PARSE_IS_SYSTEM_DIR
2590                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2591
2592            mParallelPackageParserCallback.findStaticOverlayPackages();
2593
2594            // Find base frameworks (resource packages without code).
2595            scanDirTracedLI(frameworkDir, mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR
2598                    | PackageParser.PARSE_IS_PRIVILEGED,
2599                    scanFlags | SCAN_NO_DEX, 0);
2600
2601            // Collected privileged system packages.
2602            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2603            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR
2606                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2607
2608            // Collect ordinary system packages.
2609            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2610            scanDirTracedLI(systemAppDir, mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM
2612                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2613
2614            // Collect all vendor packages.
2615            File vendorAppDir = new File("/vendor/app");
2616            try {
2617                vendorAppDir = vendorAppDir.getCanonicalFile();
2618            } catch (IOException e) {
2619                // failed to look up canonical path, continue with original one
2620            }
2621            scanDirTracedLI(vendorAppDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2624
2625            // Collect all OEM packages.
2626            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2627            scanDirTracedLI(oemAppDir, mDefParseFlags
2628                    | PackageParser.PARSE_IS_SYSTEM
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2630
2631            // Prune any system packages that no longer exist.
2632            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2633            if (!mOnlyCore) {
2634                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2635                while (psit.hasNext()) {
2636                    PackageSetting ps = psit.next();
2637
2638                    /*
2639                     * If this is not a system app, it can't be a
2640                     * disable system app.
2641                     */
2642                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2643                        continue;
2644                    }
2645
2646                    /*
2647                     * If the package is scanned, it's not erased.
2648                     */
2649                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2650                    if (scannedPkg != null) {
2651                        /*
2652                         * If the system app is both scanned and in the
2653                         * disabled packages list, then it must have been
2654                         * added via OTA. Remove it from the currently
2655                         * scanned package so the previously user-installed
2656                         * application can be scanned.
2657                         */
2658                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2659                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2660                                    + ps.name + "; removing system app.  Last known codePath="
2661                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2662                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2663                                    + scannedPkg.mVersionCode);
2664                            removePackageLI(scannedPkg, true);
2665                            mExpectingBetter.put(ps.name, ps.codePath);
2666                        }
2667
2668                        continue;
2669                    }
2670
2671                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2672                        psit.remove();
2673                        logCriticalInfo(Log.WARN, "System package " + ps.name
2674                                + " no longer exists; it's data will be wiped");
2675                        // Actual deletion of code and data will be handled by later
2676                        // reconciliation step
2677                    } else {
2678                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2679                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2680                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2681                        }
2682                    }
2683                }
2684            }
2685
2686            //look for any incomplete package installations
2687            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2688            for (int i = 0; i < deletePkgsList.size(); i++) {
2689                // Actual deletion of code and data will be handled by later
2690                // reconciliation step
2691                final String packageName = deletePkgsList.get(i).name;
2692                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2693                synchronized (mPackages) {
2694                    mSettings.removePackageLPw(packageName);
2695                }
2696            }
2697
2698            //delete tmp files
2699            deleteTempPackageFiles();
2700
2701            // Remove any shared userIDs that have no associated packages
2702            mSettings.pruneSharedUsersLPw();
2703
2704            if (!mOnlyCore) {
2705                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2706                        SystemClock.uptimeMillis());
2707                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2708
2709                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2710                        | PackageParser.PARSE_FORWARD_LOCK,
2711                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2712
2713                /**
2714                 * Remove disable package settings for any updated system
2715                 * apps that were removed via an OTA. If they're not a
2716                 * previously-updated app, remove them completely.
2717                 * Otherwise, just revoke their system-level permissions.
2718                 */
2719                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2720                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2721                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2722
2723                    String msg;
2724                    if (deletedPkg == null) {
2725                        msg = "Updated system package " + deletedAppName
2726                                + " no longer exists; it's data will be wiped";
2727                        // Actual deletion of code and data will be handled by later
2728                        // reconciliation step
2729                    } else {
2730                        msg = "Updated system app + " + deletedAppName
2731                                + " no longer present; removing system privileges for "
2732                                + deletedAppName;
2733
2734                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2735
2736                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2737                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2738                    }
2739                    logCriticalInfo(Log.WARN, msg);
2740                }
2741
2742                /**
2743                 * Make sure all system apps that we expected to appear on
2744                 * the userdata partition actually showed up. If they never
2745                 * appeared, crawl back and revive the system version.
2746                 */
2747                for (int i = 0; i < mExpectingBetter.size(); i++) {
2748                    final String packageName = mExpectingBetter.keyAt(i);
2749                    if (!mPackages.containsKey(packageName)) {
2750                        final File scanFile = mExpectingBetter.valueAt(i);
2751
2752                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2753                                + " but never showed up; reverting to system");
2754
2755                        int reparseFlags = mDefParseFlags;
2756                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2757                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2758                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2759                                    | PackageParser.PARSE_IS_PRIVILEGED;
2760                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2761                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2762                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2763                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2764                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2765                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2766                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2767                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2768                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2769                        } else {
2770                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2771                            continue;
2772                        }
2773
2774                        mSettings.enableSystemPackageLPw(packageName);
2775
2776                        try {
2777                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2778                        } catch (PackageManagerException e) {
2779                            Slog.e(TAG, "Failed to parse original system package: "
2780                                    + e.getMessage());
2781                        }
2782                    }
2783                }
2784            }
2785            mExpectingBetter.clear();
2786
2787            // Resolve the storage manager.
2788            mStorageManagerPackage = getStorageManagerPackageName();
2789
2790            // Resolve protected action filters. Only the setup wizard is allowed to
2791            // have a high priority filter for these actions.
2792            mSetupWizardPackage = getSetupWizardPackageName();
2793            if (mProtectedFilters.size() > 0) {
2794                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2795                    Slog.i(TAG, "No setup wizard;"
2796                        + " All protected intents capped to priority 0");
2797                }
2798                for (ActivityIntentInfo filter : mProtectedFilters) {
2799                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2800                        if (DEBUG_FILTERS) {
2801                            Slog.i(TAG, "Found setup wizard;"
2802                                + " allow priority " + filter.getPriority() + ";"
2803                                + " package: " + filter.activity.info.packageName
2804                                + " activity: " + filter.activity.className
2805                                + " priority: " + filter.getPriority());
2806                        }
2807                        // skip setup wizard; allow it to keep the high priority filter
2808                        continue;
2809                    }
2810                    if (DEBUG_FILTERS) {
2811                        Slog.i(TAG, "Protected action; cap priority to 0;"
2812                                + " package: " + filter.activity.info.packageName
2813                                + " activity: " + filter.activity.className
2814                                + " origPrio: " + filter.getPriority());
2815                    }
2816                    filter.setPriority(0);
2817                }
2818            }
2819            mDeferProtectedFilters = false;
2820            mProtectedFilters.clear();
2821
2822            // Now that we know all of the shared libraries, update all clients to have
2823            // the correct library paths.
2824            updateAllSharedLibrariesLPw(null);
2825
2826            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2827                // NOTE: We ignore potential failures here during a system scan (like
2828                // the rest of the commands above) because there's precious little we
2829                // can do about it. A settings error is reported, though.
2830                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2831            }
2832
2833            // Now that we know all the packages we are keeping,
2834            // read and update their last usage times.
2835            mPackageUsage.read(mPackages);
2836            mCompilerStats.read();
2837
2838            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2839                    SystemClock.uptimeMillis());
2840            Slog.i(TAG, "Time to scan packages: "
2841                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2842                    + " seconds");
2843
2844            // If the platform SDK has changed since the last time we booted,
2845            // we need to re-grant app permission to catch any new ones that
2846            // appear.  This is really a hack, and means that apps can in some
2847            // cases get permissions that the user didn't initially explicitly
2848            // allow...  it would be nice to have some better way to handle
2849            // this situation.
2850            int updateFlags = UPDATE_PERMISSIONS_ALL;
2851            if (ver.sdkVersion != mSdkVersion) {
2852                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2853                        + mSdkVersion + "; regranting permissions for internal storage");
2854                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2855            }
2856            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2857            ver.sdkVersion = mSdkVersion;
2858
2859            // If this is the first boot or an update from pre-M, and it is a normal
2860            // boot, then we need to initialize the default preferred apps across
2861            // all defined users.
2862            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2863                for (UserInfo user : sUserManager.getUsers(true)) {
2864                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2865                    applyFactoryDefaultBrowserLPw(user.id);
2866                    primeDomainVerificationsLPw(user.id);
2867                }
2868            }
2869
2870            // Prepare storage for system user really early during boot,
2871            // since core system apps like SettingsProvider and SystemUI
2872            // can't wait for user to start
2873            final int storageFlags;
2874            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2875                storageFlags = StorageManager.FLAG_STORAGE_DE;
2876            } else {
2877                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2878            }
2879            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2880                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2881                    true /* onlyCoreApps */);
2882            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2883                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2884                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2885                traceLog.traceBegin("AppDataFixup");
2886                try {
2887                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2888                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2889                } catch (InstallerException e) {
2890                    Slog.w(TAG, "Trouble fixing GIDs", e);
2891                }
2892                traceLog.traceEnd();
2893
2894                traceLog.traceBegin("AppDataPrepare");
2895                if (deferPackages == null || deferPackages.isEmpty()) {
2896                    return;
2897                }
2898                int count = 0;
2899                for (String pkgName : deferPackages) {
2900                    PackageParser.Package pkg = null;
2901                    synchronized (mPackages) {
2902                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2903                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2904                            pkg = ps.pkg;
2905                        }
2906                    }
2907                    if (pkg != null) {
2908                        synchronized (mInstallLock) {
2909                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2910                                    true /* maybeMigrateAppData */);
2911                        }
2912                        count++;
2913                    }
2914                }
2915                traceLog.traceEnd();
2916                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2917            }, "prepareAppData");
2918
2919            // If this is first boot after an OTA, and a normal boot, then
2920            // we need to clear code cache directories.
2921            // Note that we do *not* clear the application profiles. These remain valid
2922            // across OTAs and are used to drive profile verification (post OTA) and
2923            // profile compilation (without waiting to collect a fresh set of profiles).
2924            if (mIsUpgrade && !onlyCore) {
2925                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2926                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2927                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2928                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2929                        // No apps are running this early, so no need to freeze
2930                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2931                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2932                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2933                    }
2934                }
2935                ver.fingerprint = Build.FINGERPRINT;
2936            }
2937
2938            checkDefaultBrowser();
2939
2940            // clear only after permissions and other defaults have been updated
2941            mExistingSystemPackages.clear();
2942            mPromoteSystemApps = false;
2943
2944            // All the changes are done during package scanning.
2945            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2946
2947            // can downgrade to reader
2948            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2949            mSettings.writeLPr();
2950            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2951            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2952                    SystemClock.uptimeMillis());
2953
2954            if (!mOnlyCore) {
2955                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2956                mRequiredInstallerPackage = getRequiredInstallerLPr();
2957                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2958                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2959                if (mIntentFilterVerifierComponent != null) {
2960                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2961                            mIntentFilterVerifierComponent);
2962                } else {
2963                    mIntentFilterVerifier = null;
2964                }
2965                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2966                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2967                        SharedLibraryInfo.VERSION_UNDEFINED);
2968                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2969                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2970                        SharedLibraryInfo.VERSION_UNDEFINED);
2971            } else {
2972                mRequiredVerifierPackage = null;
2973                mRequiredInstallerPackage = null;
2974                mRequiredUninstallerPackage = null;
2975                mIntentFilterVerifierComponent = null;
2976                mIntentFilterVerifier = null;
2977                mServicesSystemSharedLibraryPackageName = null;
2978                mSharedSystemSharedLibraryPackageName = null;
2979            }
2980
2981            mInstallerService = new PackageInstallerService(context, this);
2982            final Pair<ComponentName, String> instantAppResolverComponent =
2983                    getInstantAppResolverLPr();
2984            if (instantAppResolverComponent != null) {
2985                if (DEBUG_EPHEMERAL) {
2986                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2987                }
2988                mInstantAppResolverConnection = new EphemeralResolverConnection(
2989                        mContext, instantAppResolverComponent.first,
2990                        instantAppResolverComponent.second);
2991                mInstantAppResolverSettingsComponent =
2992                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2993            } else {
2994                mInstantAppResolverConnection = null;
2995                mInstantAppResolverSettingsComponent = null;
2996            }
2997            updateInstantAppInstallerLocked(null);
2998
2999            // Read and update the usage of dex files.
3000            // Do this at the end of PM init so that all the packages have their
3001            // data directory reconciled.
3002            // At this point we know the code paths of the packages, so we can validate
3003            // the disk file and build the internal cache.
3004            // The usage file is expected to be small so loading and verifying it
3005            // should take a fairly small time compare to the other activities (e.g. package
3006            // scanning).
3007            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3008            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3009            for (int userId : currentUserIds) {
3010                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3011            }
3012            mDexManager.load(userPackages);
3013        } // synchronized (mPackages)
3014        } // synchronized (mInstallLock)
3015
3016        // Now after opening every single application zip, make sure they
3017        // are all flushed.  Not really needed, but keeps things nice and
3018        // tidy.
3019        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3020        Runtime.getRuntime().gc();
3021        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3022
3023        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3024        FallbackCategoryProvider.loadFallbacks();
3025        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3026
3027        // The initial scanning above does many calls into installd while
3028        // holding the mPackages lock, but we're mostly interested in yelling
3029        // once we have a booted system.
3030        mInstaller.setWarnIfHeld(mPackages);
3031
3032        // Expose private service for system components to use.
3033        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3034        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3035    }
3036
3037    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3038        // we're only interested in updating the installer appliction when 1) it's not
3039        // already set or 2) the modified package is the installer
3040        if (mInstantAppInstallerActivity != null
3041                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3042                        .equals(modifiedPackage)) {
3043            return;
3044        }
3045        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3046    }
3047
3048    private static File preparePackageParserCache(boolean isUpgrade) {
3049        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3050            return null;
3051        }
3052
3053        // Disable package parsing on eng builds to allow for faster incremental development.
3054        if ("eng".equals(Build.TYPE)) {
3055            return null;
3056        }
3057
3058        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3059            Slog.i(TAG, "Disabling package parser cache due to system property.");
3060            return null;
3061        }
3062
3063        // The base directory for the package parser cache lives under /data/system/.
3064        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3065                "package_cache");
3066        if (cacheBaseDir == null) {
3067            return null;
3068        }
3069
3070        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3071        // This also serves to "GC" unused entries when the package cache version changes (which
3072        // can only happen during upgrades).
3073        if (isUpgrade) {
3074            FileUtils.deleteContents(cacheBaseDir);
3075        }
3076
3077
3078        // Return the versioned package cache directory. This is something like
3079        // "/data/system/package_cache/1"
3080        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3081
3082        // The following is a workaround to aid development on non-numbered userdebug
3083        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3084        // the system partition is newer.
3085        //
3086        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3087        // that starts with "eng." to signify that this is an engineering build and not
3088        // destined for release.
3089        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3090            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3091
3092            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3093            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3094            // in general and should not be used for production changes. In this specific case,
3095            // we know that they will work.
3096            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3097            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3098                FileUtils.deleteContents(cacheBaseDir);
3099                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3100            }
3101        }
3102
3103        return cacheDir;
3104    }
3105
3106    @Override
3107    public boolean isFirstBoot() {
3108        // allow instant applications
3109        return mFirstBoot;
3110    }
3111
3112    @Override
3113    public boolean isOnlyCoreApps() {
3114        // allow instant applications
3115        return mOnlyCore;
3116    }
3117
3118    @Override
3119    public boolean isUpgrade() {
3120        // allow instant applications
3121        return mIsUpgrade;
3122    }
3123
3124    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3125        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3126
3127        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3128                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3129                UserHandle.USER_SYSTEM);
3130        if (matches.size() == 1) {
3131            return matches.get(0).getComponentInfo().packageName;
3132        } else if (matches.size() == 0) {
3133            Log.e(TAG, "There should probably be a verifier, but, none were found");
3134            return null;
3135        }
3136        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3137    }
3138
3139    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3140        synchronized (mPackages) {
3141            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3142            if (libraryEntry == null) {
3143                throw new IllegalStateException("Missing required shared library:" + name);
3144            }
3145            return libraryEntry.apk;
3146        }
3147    }
3148
3149    private @NonNull String getRequiredInstallerLPr() {
3150        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3151        intent.addCategory(Intent.CATEGORY_DEFAULT);
3152        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3153
3154        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3155                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3156                UserHandle.USER_SYSTEM);
3157        if (matches.size() == 1) {
3158            ResolveInfo resolveInfo = matches.get(0);
3159            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3160                throw new RuntimeException("The installer must be a privileged app");
3161            }
3162            return matches.get(0).getComponentInfo().packageName;
3163        } else {
3164            throw new RuntimeException("There must be exactly one installer; found " + matches);
3165        }
3166    }
3167
3168    private @NonNull String getRequiredUninstallerLPr() {
3169        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3170        intent.addCategory(Intent.CATEGORY_DEFAULT);
3171        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3172
3173        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3174                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3175                UserHandle.USER_SYSTEM);
3176        if (resolveInfo == null ||
3177                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3178            throw new RuntimeException("There must be exactly one uninstaller; found "
3179                    + resolveInfo);
3180        }
3181        return resolveInfo.getComponentInfo().packageName;
3182    }
3183
3184    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3185        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3186
3187        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3188                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3189                UserHandle.USER_SYSTEM);
3190        ResolveInfo best = null;
3191        final int N = matches.size();
3192        for (int i = 0; i < N; i++) {
3193            final ResolveInfo cur = matches.get(i);
3194            final String packageName = cur.getComponentInfo().packageName;
3195            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3196                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3197                continue;
3198            }
3199
3200            if (best == null || cur.priority > best.priority) {
3201                best = cur;
3202            }
3203        }
3204
3205        if (best != null) {
3206            return best.getComponentInfo().getComponentName();
3207        }
3208        Slog.w(TAG, "Intent filter verifier not found");
3209        return null;
3210    }
3211
3212    @Override
3213    public @Nullable ComponentName getInstantAppResolverComponent() {
3214        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3215            return null;
3216        }
3217        synchronized (mPackages) {
3218            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3219            if (instantAppResolver == null) {
3220                return null;
3221            }
3222            return instantAppResolver.first;
3223        }
3224    }
3225
3226    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3227        final String[] packageArray =
3228                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3229        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3230            if (DEBUG_EPHEMERAL) {
3231                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3232            }
3233            return null;
3234        }
3235
3236        final int callingUid = Binder.getCallingUid();
3237        final int resolveFlags =
3238                MATCH_DIRECT_BOOT_AWARE
3239                | MATCH_DIRECT_BOOT_UNAWARE
3240                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3241        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3242        final Intent resolverIntent = new Intent(actionName);
3243        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3244                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3245        // temporarily look for the old action
3246        if (resolvers.size() == 0) {
3247            if (DEBUG_EPHEMERAL) {
3248                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3249            }
3250            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3251            resolverIntent.setAction(actionName);
3252            resolvers = queryIntentServicesInternal(resolverIntent, null,
3253                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3254        }
3255        final int N = resolvers.size();
3256        if (N == 0) {
3257            if (DEBUG_EPHEMERAL) {
3258                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3259            }
3260            return null;
3261        }
3262
3263        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3264        for (int i = 0; i < N; i++) {
3265            final ResolveInfo info = resolvers.get(i);
3266
3267            if (info.serviceInfo == null) {
3268                continue;
3269            }
3270
3271            final String packageName = info.serviceInfo.packageName;
3272            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3273                if (DEBUG_EPHEMERAL) {
3274                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3275                            + " pkg: " + packageName + ", info:" + info);
3276                }
3277                continue;
3278            }
3279
3280            if (DEBUG_EPHEMERAL) {
3281                Slog.v(TAG, "Ephemeral resolver found;"
3282                        + " pkg: " + packageName + ", info:" + info);
3283            }
3284            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3285        }
3286        if (DEBUG_EPHEMERAL) {
3287            Slog.v(TAG, "Ephemeral resolver NOT found");
3288        }
3289        return null;
3290    }
3291
3292    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3293        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3294        intent.addCategory(Intent.CATEGORY_DEFAULT);
3295        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3296
3297        final int resolveFlags =
3298                MATCH_DIRECT_BOOT_AWARE
3299                | MATCH_DIRECT_BOOT_UNAWARE
3300                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3301        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3302                resolveFlags, UserHandle.USER_SYSTEM);
3303        // temporarily look for the old action
3304        if (matches.isEmpty()) {
3305            if (DEBUG_EPHEMERAL) {
3306                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3307            }
3308            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3309            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3310                    resolveFlags, UserHandle.USER_SYSTEM);
3311        }
3312        Iterator<ResolveInfo> iter = matches.iterator();
3313        while (iter.hasNext()) {
3314            final ResolveInfo rInfo = iter.next();
3315            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3316            if (ps != null) {
3317                final PermissionsState permissionsState = ps.getPermissionsState();
3318                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3319                    continue;
3320                }
3321            }
3322            iter.remove();
3323        }
3324        if (matches.size() == 0) {
3325            return null;
3326        } else if (matches.size() == 1) {
3327            return (ActivityInfo) matches.get(0).getComponentInfo();
3328        } else {
3329            throw new RuntimeException(
3330                    "There must be at most one ephemeral installer; found " + matches);
3331        }
3332    }
3333
3334    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3335            @NonNull ComponentName resolver) {
3336        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3337                .addCategory(Intent.CATEGORY_DEFAULT)
3338                .setPackage(resolver.getPackageName());
3339        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3340        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3341                UserHandle.USER_SYSTEM);
3342        // temporarily look for the old action
3343        if (matches.isEmpty()) {
3344            if (DEBUG_EPHEMERAL) {
3345                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3346            }
3347            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3348            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3349                    UserHandle.USER_SYSTEM);
3350        }
3351        if (matches.isEmpty()) {
3352            return null;
3353        }
3354        return matches.get(0).getComponentInfo().getComponentName();
3355    }
3356
3357    private void primeDomainVerificationsLPw(int userId) {
3358        if (DEBUG_DOMAIN_VERIFICATION) {
3359            Slog.d(TAG, "Priming domain verifications in user " + userId);
3360        }
3361
3362        SystemConfig systemConfig = SystemConfig.getInstance();
3363        ArraySet<String> packages = systemConfig.getLinkedApps();
3364
3365        for (String packageName : packages) {
3366            PackageParser.Package pkg = mPackages.get(packageName);
3367            if (pkg != null) {
3368                if (!pkg.isSystemApp()) {
3369                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3370                    continue;
3371                }
3372
3373                ArraySet<String> domains = null;
3374                for (PackageParser.Activity a : pkg.activities) {
3375                    for (ActivityIntentInfo filter : a.intents) {
3376                        if (hasValidDomains(filter)) {
3377                            if (domains == null) {
3378                                domains = new ArraySet<String>();
3379                            }
3380                            domains.addAll(filter.getHostsList());
3381                        }
3382                    }
3383                }
3384
3385                if (domains != null && domains.size() > 0) {
3386                    if (DEBUG_DOMAIN_VERIFICATION) {
3387                        Slog.v(TAG, "      + " + packageName);
3388                    }
3389                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3390                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3391                    // and then 'always' in the per-user state actually used for intent resolution.
3392                    final IntentFilterVerificationInfo ivi;
3393                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3394                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3395                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3396                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3397                } else {
3398                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3399                            + "' does not handle web links");
3400                }
3401            } else {
3402                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3403            }
3404        }
3405
3406        scheduleWritePackageRestrictionsLocked(userId);
3407        scheduleWriteSettingsLocked();
3408    }
3409
3410    private void applyFactoryDefaultBrowserLPw(int userId) {
3411        // The default browser app's package name is stored in a string resource,
3412        // with a product-specific overlay used for vendor customization.
3413        String browserPkg = mContext.getResources().getString(
3414                com.android.internal.R.string.default_browser);
3415        if (!TextUtils.isEmpty(browserPkg)) {
3416            // non-empty string => required to be a known package
3417            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3418            if (ps == null) {
3419                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3420                browserPkg = null;
3421            } else {
3422                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3423            }
3424        }
3425
3426        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3427        // default.  If there's more than one, just leave everything alone.
3428        if (browserPkg == null) {
3429            calculateDefaultBrowserLPw(userId);
3430        }
3431    }
3432
3433    private void calculateDefaultBrowserLPw(int userId) {
3434        List<String> allBrowsers = resolveAllBrowserApps(userId);
3435        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3436        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3437    }
3438
3439    private List<String> resolveAllBrowserApps(int userId) {
3440        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3441        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3442                PackageManager.MATCH_ALL, userId);
3443
3444        final int count = list.size();
3445        List<String> result = new ArrayList<String>(count);
3446        for (int i=0; i<count; i++) {
3447            ResolveInfo info = list.get(i);
3448            if (info.activityInfo == null
3449                    || !info.handleAllWebDataURI
3450                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3451                    || result.contains(info.activityInfo.packageName)) {
3452                continue;
3453            }
3454            result.add(info.activityInfo.packageName);
3455        }
3456
3457        return result;
3458    }
3459
3460    private boolean packageIsBrowser(String packageName, int userId) {
3461        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3462                PackageManager.MATCH_ALL, userId);
3463        final int N = list.size();
3464        for (int i = 0; i < N; i++) {
3465            ResolveInfo info = list.get(i);
3466            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3467                return true;
3468            }
3469        }
3470        return false;
3471    }
3472
3473    private void checkDefaultBrowser() {
3474        final int myUserId = UserHandle.myUserId();
3475        final String packageName = getDefaultBrowserPackageName(myUserId);
3476        if (packageName != null) {
3477            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3478            if (info == null) {
3479                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3480                synchronized (mPackages) {
3481                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3482                }
3483            }
3484        }
3485    }
3486
3487    @Override
3488    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3489            throws RemoteException {
3490        try {
3491            return super.onTransact(code, data, reply, flags);
3492        } catch (RuntimeException e) {
3493            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3494                Slog.wtf(TAG, "Package Manager Crash", e);
3495            }
3496            throw e;
3497        }
3498    }
3499
3500    static int[] appendInts(int[] cur, int[] add) {
3501        if (add == null) return cur;
3502        if (cur == null) return add;
3503        final int N = add.length;
3504        for (int i=0; i<N; i++) {
3505            cur = appendInt(cur, add[i]);
3506        }
3507        return cur;
3508    }
3509
3510    /**
3511     * Returns whether or not a full application can see an instant application.
3512     * <p>
3513     * Currently, there are three cases in which this can occur:
3514     * <ol>
3515     * <li>The calling application is a "special" process. The special
3516     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3517     *     and {@code 0}</li>
3518     * <li>The calling application has the permission
3519     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3520     * <li>The calling application is the default launcher on the
3521     *     system partition.</li>
3522     * </ol>
3523     */
3524    private boolean canViewInstantApps(int callingUid, int userId) {
3525        if (callingUid == Process.SYSTEM_UID
3526                || callingUid == Process.SHELL_UID
3527                || callingUid == Process.ROOT_UID) {
3528            return true;
3529        }
3530        if (mContext.checkCallingOrSelfPermission(
3531                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3532            return true;
3533        }
3534        if (mContext.checkCallingOrSelfPermission(
3535                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3536            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3537            if (homeComponent != null
3538                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3539                return true;
3540            }
3541        }
3542        return false;
3543    }
3544
3545    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3546        if (!sUserManager.exists(userId)) return null;
3547        if (ps == null) {
3548            return null;
3549        }
3550        PackageParser.Package p = ps.pkg;
3551        if (p == null) {
3552            return null;
3553        }
3554        final int callingUid = Binder.getCallingUid();
3555        // Filter out ephemeral app metadata:
3556        //   * The system/shell/root can see metadata for any app
3557        //   * An installed app can see metadata for 1) other installed apps
3558        //     and 2) ephemeral apps that have explicitly interacted with it
3559        //   * Ephemeral apps can only see their own data and exposed installed apps
3560        //   * Holding a signature permission allows seeing instant apps
3561        if (filterAppAccessLPr(ps, callingUid, userId)) {
3562            return null;
3563        }
3564
3565        final PermissionsState permissionsState = ps.getPermissionsState();
3566
3567        // Compute GIDs only if requested
3568        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3569                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3570        // Compute granted permissions only if package has requested permissions
3571        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3572                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3573        final PackageUserState state = ps.readUserState(userId);
3574
3575        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3576                && ps.isSystem()) {
3577            flags |= MATCH_ANY_USER;
3578        }
3579
3580        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3581                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3582
3583        if (packageInfo == null) {
3584            return null;
3585        }
3586
3587        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3588                resolveExternalPackageNameLPr(p);
3589
3590        return packageInfo;
3591    }
3592
3593    @Override
3594    public void checkPackageStartable(String packageName, int userId) {
3595        final int callingUid = Binder.getCallingUid();
3596        if (getInstantAppPackageName(callingUid) != null) {
3597            throw new SecurityException("Instant applications don't have access to this method");
3598        }
3599        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3600        synchronized (mPackages) {
3601            final PackageSetting ps = mSettings.mPackages.get(packageName);
3602            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3603                throw new SecurityException("Package " + packageName + " was not found!");
3604            }
3605
3606            if (!ps.getInstalled(userId)) {
3607                throw new SecurityException(
3608                        "Package " + packageName + " was not installed for user " + userId + "!");
3609            }
3610
3611            if (mSafeMode && !ps.isSystem()) {
3612                throw new SecurityException("Package " + packageName + " not a system app!");
3613            }
3614
3615            if (mFrozenPackages.contains(packageName)) {
3616                throw new SecurityException("Package " + packageName + " is currently frozen!");
3617            }
3618
3619            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3620                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3621                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3622            }
3623        }
3624    }
3625
3626    @Override
3627    public boolean isPackageAvailable(String packageName, int userId) {
3628        if (!sUserManager.exists(userId)) return false;
3629        final int callingUid = Binder.getCallingUid();
3630        enforceCrossUserPermission(callingUid, userId,
3631                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3632        synchronized (mPackages) {
3633            PackageParser.Package p = mPackages.get(packageName);
3634            if (p != null) {
3635                final PackageSetting ps = (PackageSetting) p.mExtras;
3636                if (filterAppAccessLPr(ps, callingUid, userId)) {
3637                    return false;
3638                }
3639                if (ps != null) {
3640                    final PackageUserState state = ps.readUserState(userId);
3641                    if (state != null) {
3642                        return PackageParser.isAvailable(state);
3643                    }
3644                }
3645            }
3646        }
3647        return false;
3648    }
3649
3650    @Override
3651    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3652        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3653                flags, Binder.getCallingUid(), userId);
3654    }
3655
3656    @Override
3657    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3658            int flags, int userId) {
3659        return getPackageInfoInternal(versionedPackage.getPackageName(),
3660                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3661    }
3662
3663    /**
3664     * Important: The provided filterCallingUid is used exclusively to filter out packages
3665     * that can be seen based on user state. It's typically the original caller uid prior
3666     * to clearing. Because it can only be provided by trusted code, it's value can be
3667     * trusted and will be used as-is; unlike userId which will be validated by this method.
3668     */
3669    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3670            int flags, int filterCallingUid, int userId) {
3671        if (!sUserManager.exists(userId)) return null;
3672        flags = updateFlagsForPackage(flags, userId, packageName);
3673        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3674                false /* requireFullPermission */, false /* checkShell */, "get package info");
3675
3676        // reader
3677        synchronized (mPackages) {
3678            // Normalize package name to handle renamed packages and static libs
3679            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3680
3681            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3682            if (matchFactoryOnly) {
3683                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3684                if (ps != null) {
3685                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3686                        return null;
3687                    }
3688                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3689                        return null;
3690                    }
3691                    return generatePackageInfo(ps, flags, userId);
3692                }
3693            }
3694
3695            PackageParser.Package p = mPackages.get(packageName);
3696            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3697                return null;
3698            }
3699            if (DEBUG_PACKAGE_INFO)
3700                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3701            if (p != null) {
3702                final PackageSetting ps = (PackageSetting) p.mExtras;
3703                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3704                    return null;
3705                }
3706                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3707                    return null;
3708                }
3709                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3710            }
3711            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3712                final PackageSetting ps = mSettings.mPackages.get(packageName);
3713                if (ps == null) return null;
3714                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3715                    return null;
3716                }
3717                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3718                    return null;
3719                }
3720                return generatePackageInfo(ps, flags, userId);
3721            }
3722        }
3723        return null;
3724    }
3725
3726    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3727        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3728            return true;
3729        }
3730        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3731            return true;
3732        }
3733        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3734            return true;
3735        }
3736        return false;
3737    }
3738
3739    private boolean isComponentVisibleToInstantApp(
3740            @Nullable ComponentName component, @ComponentType int type) {
3741        if (type == TYPE_ACTIVITY) {
3742            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3743            return activity != null
3744                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3745                    : false;
3746        } else if (type == TYPE_RECEIVER) {
3747            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3748            return activity != null
3749                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3750                    : false;
3751        } else if (type == TYPE_SERVICE) {
3752            final PackageParser.Service service = mServices.mServices.get(component);
3753            return service != null
3754                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3755                    : false;
3756        } else if (type == TYPE_PROVIDER) {
3757            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3758            return provider != null
3759                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3760                    : false;
3761        } else if (type == TYPE_UNKNOWN) {
3762            return isComponentVisibleToInstantApp(component);
3763        }
3764        return false;
3765    }
3766
3767    /**
3768     * Returns whether or not access to the application should be filtered.
3769     * <p>
3770     * Access may be limited based upon whether the calling or target applications
3771     * are instant applications.
3772     *
3773     * @see #canAccessInstantApps(int)
3774     */
3775    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3776            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3777        // if we're in an isolated process, get the real calling UID
3778        if (Process.isIsolated(callingUid)) {
3779            callingUid = mIsolatedOwners.get(callingUid);
3780        }
3781        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3782        final boolean callerIsInstantApp = instantAppPkgName != null;
3783        if (ps == null) {
3784            if (callerIsInstantApp) {
3785                // pretend the application exists, but, needs to be filtered
3786                return true;
3787            }
3788            return false;
3789        }
3790        // if the target and caller are the same application, don't filter
3791        if (isCallerSameApp(ps.name, callingUid)) {
3792            return false;
3793        }
3794        if (callerIsInstantApp) {
3795            // request for a specific component; if it hasn't been explicitly exposed, filter
3796            if (component != null) {
3797                return !isComponentVisibleToInstantApp(component, componentType);
3798            }
3799            // request for application; if no components have been explicitly exposed, filter
3800            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3801        }
3802        if (ps.getInstantApp(userId)) {
3803            // caller can see all components of all instant applications, don't filter
3804            if (canViewInstantApps(callingUid, userId)) {
3805                return false;
3806            }
3807            // request for a specific instant application component, filter
3808            if (component != null) {
3809                return true;
3810            }
3811            // request for an instant application; if the caller hasn't been granted access, filter
3812            return !mInstantAppRegistry.isInstantAccessGranted(
3813                    userId, UserHandle.getAppId(callingUid), ps.appId);
3814        }
3815        return false;
3816    }
3817
3818    /**
3819     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3820     */
3821    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3822        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3823    }
3824
3825    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3826            int flags) {
3827        // Callers can access only the libs they depend on, otherwise they need to explicitly
3828        // ask for the shared libraries given the caller is allowed to access all static libs.
3829        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3830            // System/shell/root get to see all static libs
3831            final int appId = UserHandle.getAppId(uid);
3832            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3833                    || appId == Process.ROOT_UID) {
3834                return false;
3835            }
3836        }
3837
3838        // No package means no static lib as it is always on internal storage
3839        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3840            return false;
3841        }
3842
3843        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3844                ps.pkg.staticSharedLibVersion);
3845        if (libEntry == null) {
3846            return false;
3847        }
3848
3849        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3850        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3851        if (uidPackageNames == null) {
3852            return true;
3853        }
3854
3855        for (String uidPackageName : uidPackageNames) {
3856            if (ps.name.equals(uidPackageName)) {
3857                return false;
3858            }
3859            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3860            if (uidPs != null) {
3861                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3862                        libEntry.info.getName());
3863                if (index < 0) {
3864                    continue;
3865                }
3866                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3867                    return false;
3868                }
3869            }
3870        }
3871        return true;
3872    }
3873
3874    @Override
3875    public String[] currentToCanonicalPackageNames(String[] names) {
3876        final int callingUid = Binder.getCallingUid();
3877        if (getInstantAppPackageName(callingUid) != null) {
3878            return names;
3879        }
3880        final String[] out = new String[names.length];
3881        // reader
3882        synchronized (mPackages) {
3883            final int callingUserId = UserHandle.getUserId(callingUid);
3884            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3885            for (int i=names.length-1; i>=0; i--) {
3886                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3887                boolean translateName = false;
3888                if (ps != null && ps.realName != null) {
3889                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3890                    translateName = !targetIsInstantApp
3891                            || canViewInstantApps
3892                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3893                                    UserHandle.getAppId(callingUid), ps.appId);
3894                }
3895                out[i] = translateName ? ps.realName : names[i];
3896            }
3897        }
3898        return out;
3899    }
3900
3901    @Override
3902    public String[] canonicalToCurrentPackageNames(String[] names) {
3903        final int callingUid = Binder.getCallingUid();
3904        if (getInstantAppPackageName(callingUid) != null) {
3905            return names;
3906        }
3907        final String[] out = new String[names.length];
3908        // reader
3909        synchronized (mPackages) {
3910            final int callingUserId = UserHandle.getUserId(callingUid);
3911            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3912            for (int i=names.length-1; i>=0; i--) {
3913                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3914                boolean translateName = false;
3915                if (cur != null) {
3916                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3917                    final boolean targetIsInstantApp =
3918                            ps != null && ps.getInstantApp(callingUserId);
3919                    translateName = !targetIsInstantApp
3920                            || canViewInstantApps
3921                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3922                                    UserHandle.getAppId(callingUid), ps.appId);
3923                }
3924                out[i] = translateName ? cur : names[i];
3925            }
3926        }
3927        return out;
3928    }
3929
3930    @Override
3931    public int getPackageUid(String packageName, int flags, int userId) {
3932        if (!sUserManager.exists(userId)) return -1;
3933        final int callingUid = Binder.getCallingUid();
3934        flags = updateFlagsForPackage(flags, userId, packageName);
3935        enforceCrossUserPermission(callingUid, userId,
3936                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3937
3938        // reader
3939        synchronized (mPackages) {
3940            final PackageParser.Package p = mPackages.get(packageName);
3941            if (p != null && p.isMatch(flags)) {
3942                PackageSetting ps = (PackageSetting) p.mExtras;
3943                if (filterAppAccessLPr(ps, callingUid, userId)) {
3944                    return -1;
3945                }
3946                return UserHandle.getUid(userId, p.applicationInfo.uid);
3947            }
3948            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3949                final PackageSetting ps = mSettings.mPackages.get(packageName);
3950                if (ps != null && ps.isMatch(flags)
3951                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3952                    return UserHandle.getUid(userId, ps.appId);
3953                }
3954            }
3955        }
3956
3957        return -1;
3958    }
3959
3960    @Override
3961    public int[] getPackageGids(String packageName, int flags, int userId) {
3962        if (!sUserManager.exists(userId)) return null;
3963        final int callingUid = Binder.getCallingUid();
3964        flags = updateFlagsForPackage(flags, userId, packageName);
3965        enforceCrossUserPermission(callingUid, userId,
3966                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3967
3968        // reader
3969        synchronized (mPackages) {
3970            final PackageParser.Package p = mPackages.get(packageName);
3971            if (p != null && p.isMatch(flags)) {
3972                PackageSetting ps = (PackageSetting) p.mExtras;
3973                if (filterAppAccessLPr(ps, callingUid, userId)) {
3974                    return null;
3975                }
3976                // TODO: Shouldn't this be checking for package installed state for userId and
3977                // return null?
3978                return ps.getPermissionsState().computeGids(userId);
3979            }
3980            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3981                final PackageSetting ps = mSettings.mPackages.get(packageName);
3982                if (ps != null && ps.isMatch(flags)
3983                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3984                    return ps.getPermissionsState().computeGids(userId);
3985                }
3986            }
3987        }
3988
3989        return null;
3990    }
3991
3992    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3993        if (bp.perm != null) {
3994            return PackageParser.generatePermissionInfo(bp.perm, flags);
3995        }
3996        PermissionInfo pi = new PermissionInfo();
3997        pi.name = bp.name;
3998        pi.packageName = bp.sourcePackage;
3999        pi.nonLocalizedLabel = bp.name;
4000        pi.protectionLevel = bp.protectionLevel;
4001        return pi;
4002    }
4003
4004    @Override
4005    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4006        final int callingUid = Binder.getCallingUid();
4007        if (getInstantAppPackageName(callingUid) != null) {
4008            return null;
4009        }
4010        // reader
4011        synchronized (mPackages) {
4012            final BasePermission p = mSettings.mPermissions.get(name);
4013            if (p == null) {
4014                return null;
4015            }
4016            // If the caller is an app that targets pre 26 SDK drop protection flags.
4017            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4018            if (permissionInfo != null) {
4019                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4020                        permissionInfo.protectionLevel, packageName, callingUid);
4021            }
4022            return permissionInfo;
4023        }
4024    }
4025
4026    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4027            String packageName, int uid) {
4028        // Signature permission flags area always reported
4029        final int protectionLevelMasked = protectionLevel
4030                & (PermissionInfo.PROTECTION_NORMAL
4031                | PermissionInfo.PROTECTION_DANGEROUS
4032                | PermissionInfo.PROTECTION_SIGNATURE);
4033        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4034            return protectionLevel;
4035        }
4036
4037        // System sees all flags.
4038        final int appId = UserHandle.getAppId(uid);
4039        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4040                || appId == Process.SHELL_UID) {
4041            return protectionLevel;
4042        }
4043
4044        // Normalize package name to handle renamed packages and static libs
4045        packageName = resolveInternalPackageNameLPr(packageName,
4046                PackageManager.VERSION_CODE_HIGHEST);
4047
4048        // Apps that target O see flags for all protection levels.
4049        final PackageSetting ps = mSettings.mPackages.get(packageName);
4050        if (ps == null) {
4051            return protectionLevel;
4052        }
4053        if (ps.appId != appId) {
4054            return protectionLevel;
4055        }
4056
4057        final PackageParser.Package pkg = mPackages.get(packageName);
4058        if (pkg == null) {
4059            return protectionLevel;
4060        }
4061        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4062            return protectionLevelMasked;
4063        }
4064
4065        return protectionLevel;
4066    }
4067
4068    @Override
4069    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4070            int flags) {
4071        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4072            return null;
4073        }
4074        // reader
4075        synchronized (mPackages) {
4076            if (group != null && !mPermissionGroups.containsKey(group)) {
4077                // This is thrown as NameNotFoundException
4078                return null;
4079            }
4080
4081            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4082            for (BasePermission p : mSettings.mPermissions.values()) {
4083                if (group == null) {
4084                    if (p.perm == null || p.perm.info.group == null) {
4085                        out.add(generatePermissionInfo(p, flags));
4086                    }
4087                } else {
4088                    if (p.perm != null && group.equals(p.perm.info.group)) {
4089                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4090                    }
4091                }
4092            }
4093            return new ParceledListSlice<>(out);
4094        }
4095    }
4096
4097    @Override
4098    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4099        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4100            return null;
4101        }
4102        // reader
4103        synchronized (mPackages) {
4104            return PackageParser.generatePermissionGroupInfo(
4105                    mPermissionGroups.get(name), flags);
4106        }
4107    }
4108
4109    @Override
4110    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4111        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4112            return ParceledListSlice.emptyList();
4113        }
4114        // reader
4115        synchronized (mPackages) {
4116            final int N = mPermissionGroups.size();
4117            ArrayList<PermissionGroupInfo> out
4118                    = new ArrayList<PermissionGroupInfo>(N);
4119            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4120                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4121            }
4122            return new ParceledListSlice<>(out);
4123        }
4124    }
4125
4126    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4127            int filterCallingUid, int userId) {
4128        if (!sUserManager.exists(userId)) return null;
4129        PackageSetting ps = mSettings.mPackages.get(packageName);
4130        if (ps != null) {
4131            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4132                return null;
4133            }
4134            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4135                return null;
4136            }
4137            if (ps.pkg == null) {
4138                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4139                if (pInfo != null) {
4140                    return pInfo.applicationInfo;
4141                }
4142                return null;
4143            }
4144            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4145                    ps.readUserState(userId), userId);
4146            if (ai != null) {
4147                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4148            }
4149            return ai;
4150        }
4151        return null;
4152    }
4153
4154    @Override
4155    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4156        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4157    }
4158
4159    /**
4160     * Important: The provided filterCallingUid is used exclusively to filter out applications
4161     * that can be seen based on user state. It's typically the original caller uid prior
4162     * to clearing. Because it can only be provided by trusted code, it's value can be
4163     * trusted and will be used as-is; unlike userId which will be validated by this method.
4164     */
4165    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4166            int filterCallingUid, int userId) {
4167        if (!sUserManager.exists(userId)) return null;
4168        flags = updateFlagsForApplication(flags, userId, packageName);
4169        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4170                false /* requireFullPermission */, false /* checkShell */, "get application info");
4171
4172        // writer
4173        synchronized (mPackages) {
4174            // Normalize package name to handle renamed packages and static libs
4175            packageName = resolveInternalPackageNameLPr(packageName,
4176                    PackageManager.VERSION_CODE_HIGHEST);
4177
4178            PackageParser.Package p = mPackages.get(packageName);
4179            if (DEBUG_PACKAGE_INFO) Log.v(
4180                    TAG, "getApplicationInfo " + packageName
4181                    + ": " + p);
4182            if (p != null) {
4183                PackageSetting ps = mSettings.mPackages.get(packageName);
4184                if (ps == null) return null;
4185                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4186                    return null;
4187                }
4188                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4189                    return null;
4190                }
4191                // Note: isEnabledLP() does not apply here - always return info
4192                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4193                        p, flags, ps.readUserState(userId), userId);
4194                if (ai != null) {
4195                    ai.packageName = resolveExternalPackageNameLPr(p);
4196                }
4197                return ai;
4198            }
4199            if ("android".equals(packageName)||"system".equals(packageName)) {
4200                return mAndroidApplication;
4201            }
4202            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4203                // Already generates the external package name
4204                return generateApplicationInfoFromSettingsLPw(packageName,
4205                        flags, filterCallingUid, userId);
4206            }
4207        }
4208        return null;
4209    }
4210
4211    private String normalizePackageNameLPr(String packageName) {
4212        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4213        return normalizedPackageName != null ? normalizedPackageName : packageName;
4214    }
4215
4216    @Override
4217    public void deletePreloadsFileCache() {
4218        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4219            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4220        }
4221        File dir = Environment.getDataPreloadsFileCacheDirectory();
4222        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4223        FileUtils.deleteContents(dir);
4224    }
4225
4226    @Override
4227    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4228            final int storageFlags, final IPackageDataObserver observer) {
4229        mContext.enforceCallingOrSelfPermission(
4230                android.Manifest.permission.CLEAR_APP_CACHE, null);
4231        mHandler.post(() -> {
4232            boolean success = false;
4233            try {
4234                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4235                success = true;
4236            } catch (IOException e) {
4237                Slog.w(TAG, e);
4238            }
4239            if (observer != null) {
4240                try {
4241                    observer.onRemoveCompleted(null, success);
4242                } catch (RemoteException e) {
4243                    Slog.w(TAG, e);
4244                }
4245            }
4246        });
4247    }
4248
4249    @Override
4250    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4251            final int storageFlags, final IntentSender pi) {
4252        mContext.enforceCallingOrSelfPermission(
4253                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4254        mHandler.post(() -> {
4255            boolean success = false;
4256            try {
4257                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4258                success = true;
4259            } catch (IOException e) {
4260                Slog.w(TAG, e);
4261            }
4262            if (pi != null) {
4263                try {
4264                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4265                } catch (SendIntentException e) {
4266                    Slog.w(TAG, e);
4267                }
4268            }
4269        });
4270    }
4271
4272    /**
4273     * Blocking call to clear various types of cached data across the system
4274     * until the requested bytes are available.
4275     */
4276    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4277        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4278        final File file = storage.findPathForUuid(volumeUuid);
4279        if (file.getUsableSpace() >= bytes) return;
4280
4281        if (ENABLE_FREE_CACHE_V2) {
4282            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4283                    volumeUuid);
4284            final boolean aggressive = (storageFlags
4285                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4286            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4287
4288            // 1. Pre-flight to determine if we have any chance to succeed
4289            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4290            if (internalVolume && (aggressive || SystemProperties
4291                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4292                deletePreloadsFileCache();
4293                if (file.getUsableSpace() >= bytes) return;
4294            }
4295
4296            // 3. Consider parsed APK data (aggressive only)
4297            if (internalVolume && aggressive) {
4298                FileUtils.deleteContents(mCacheDir);
4299                if (file.getUsableSpace() >= bytes) return;
4300            }
4301
4302            // 4. Consider cached app data (above quotas)
4303            try {
4304                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4305                        Installer.FLAG_FREE_CACHE_V2);
4306            } catch (InstallerException ignored) {
4307            }
4308            if (file.getUsableSpace() >= bytes) return;
4309
4310            // 5. Consider shared libraries with refcount=0 and age>min cache period
4311            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4312                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4313                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4314                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4315                return;
4316            }
4317
4318            // 6. Consider dexopt output (aggressive only)
4319            // TODO: Implement
4320
4321            // 7. Consider installed instant apps unused longer than min cache period
4322            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4323                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4324                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4325                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4326                return;
4327            }
4328
4329            // 8. Consider cached app data (below quotas)
4330            try {
4331                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4332                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4333            } catch (InstallerException ignored) {
4334            }
4335            if (file.getUsableSpace() >= bytes) return;
4336
4337            // 9. Consider DropBox entries
4338            // TODO: Implement
4339
4340            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4341            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4342                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4343                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4344                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4345                return;
4346            }
4347        } else {
4348            try {
4349                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4350            } catch (InstallerException ignored) {
4351            }
4352            if (file.getUsableSpace() >= bytes) return;
4353        }
4354
4355        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4356    }
4357
4358    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4359            throws IOException {
4360        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4361        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4362
4363        List<VersionedPackage> packagesToDelete = null;
4364        final long now = System.currentTimeMillis();
4365
4366        synchronized (mPackages) {
4367            final int[] allUsers = sUserManager.getUserIds();
4368            final int libCount = mSharedLibraries.size();
4369            for (int i = 0; i < libCount; i++) {
4370                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4371                if (versionedLib == null) {
4372                    continue;
4373                }
4374                final int versionCount = versionedLib.size();
4375                for (int j = 0; j < versionCount; j++) {
4376                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4377                    // Skip packages that are not static shared libs.
4378                    if (!libInfo.isStatic()) {
4379                        break;
4380                    }
4381                    // Important: We skip static shared libs used for some user since
4382                    // in such a case we need to keep the APK on the device. The check for
4383                    // a lib being used for any user is performed by the uninstall call.
4384                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4385                    // Resolve the package name - we use synthetic package names internally
4386                    final String internalPackageName = resolveInternalPackageNameLPr(
4387                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4388                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4389                    // Skip unused static shared libs cached less than the min period
4390                    // to prevent pruning a lib needed by a subsequently installed package.
4391                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4392                        continue;
4393                    }
4394                    if (packagesToDelete == null) {
4395                        packagesToDelete = new ArrayList<>();
4396                    }
4397                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4398                            declaringPackage.getVersionCode()));
4399                }
4400            }
4401        }
4402
4403        if (packagesToDelete != null) {
4404            final int packageCount = packagesToDelete.size();
4405            for (int i = 0; i < packageCount; i++) {
4406                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4407                // Delete the package synchronously (will fail of the lib used for any user).
4408                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4409                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4410                                == PackageManager.DELETE_SUCCEEDED) {
4411                    if (volume.getUsableSpace() >= neededSpace) {
4412                        return true;
4413                    }
4414                }
4415            }
4416        }
4417
4418        return false;
4419    }
4420
4421    /**
4422     * Update given flags based on encryption status of current user.
4423     */
4424    private int updateFlags(int flags, int userId) {
4425        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4426                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4427            // Caller expressed an explicit opinion about what encryption
4428            // aware/unaware components they want to see, so fall through and
4429            // give them what they want
4430        } else {
4431            // Caller expressed no opinion, so match based on user state
4432            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4433                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4434            } else {
4435                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4436            }
4437        }
4438        return flags;
4439    }
4440
4441    private UserManagerInternal getUserManagerInternal() {
4442        if (mUserManagerInternal == null) {
4443            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4444        }
4445        return mUserManagerInternal;
4446    }
4447
4448    private DeviceIdleController.LocalService getDeviceIdleController() {
4449        if (mDeviceIdleController == null) {
4450            mDeviceIdleController =
4451                    LocalServices.getService(DeviceIdleController.LocalService.class);
4452        }
4453        return mDeviceIdleController;
4454    }
4455
4456    /**
4457     * Update given flags when being used to request {@link PackageInfo}.
4458     */
4459    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4460        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4461        boolean triaged = true;
4462        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4463                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4464            // Caller is asking for component details, so they'd better be
4465            // asking for specific encryption matching behavior, or be triaged
4466            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4467                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4468                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4469                triaged = false;
4470            }
4471        }
4472        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4473                | PackageManager.MATCH_SYSTEM_ONLY
4474                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4475            triaged = false;
4476        }
4477        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4478            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4479                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4480                    + Debug.getCallers(5));
4481        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4482                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4483            // If the caller wants all packages and has a restricted profile associated with it,
4484            // then match all users. This is to make sure that launchers that need to access work
4485            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4486            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4487            flags |= PackageManager.MATCH_ANY_USER;
4488        }
4489        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4490            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4491                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4492        }
4493        return updateFlags(flags, userId);
4494    }
4495
4496    /**
4497     * Update given flags when being used to request {@link ApplicationInfo}.
4498     */
4499    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4500        return updateFlagsForPackage(flags, userId, cookie);
4501    }
4502
4503    /**
4504     * Update given flags when being used to request {@link ComponentInfo}.
4505     */
4506    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4507        if (cookie instanceof Intent) {
4508            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4509                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4510            }
4511        }
4512
4513        boolean triaged = true;
4514        // Caller is asking for component details, so they'd better be
4515        // asking for specific encryption matching behavior, or be triaged
4516        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4517                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4518                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4519            triaged = false;
4520        }
4521        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4522            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4523                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4524        }
4525
4526        return updateFlags(flags, userId);
4527    }
4528
4529    /**
4530     * Update given intent when being used to request {@link ResolveInfo}.
4531     */
4532    private Intent updateIntentForResolve(Intent intent) {
4533        if (intent.getSelector() != null) {
4534            intent = intent.getSelector();
4535        }
4536        if (DEBUG_PREFERRED) {
4537            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4538        }
4539        return intent;
4540    }
4541
4542    /**
4543     * Update given flags when being used to request {@link ResolveInfo}.
4544     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4545     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4546     * flag set. However, this flag is only honoured in three circumstances:
4547     * <ul>
4548     * <li>when called from a system process</li>
4549     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4550     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4551     * action and a {@code android.intent.category.BROWSABLE} category</li>
4552     * </ul>
4553     */
4554    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4555        return updateFlagsForResolve(flags, userId, intent, callingUid,
4556                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4557    }
4558    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4559            boolean wantInstantApps) {
4560        return updateFlagsForResolve(flags, userId, intent, callingUid,
4561                wantInstantApps, false /*onlyExposedExplicitly*/);
4562    }
4563    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4564            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4565        // Safe mode means we shouldn't match any third-party components
4566        if (mSafeMode) {
4567            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4568        }
4569        if (getInstantAppPackageName(callingUid) != null) {
4570            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4571            if (onlyExposedExplicitly) {
4572                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4573            }
4574            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4575            flags |= PackageManager.MATCH_INSTANT;
4576        } else {
4577            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4578            final boolean allowMatchInstant =
4579                    (wantInstantApps
4580                            && Intent.ACTION_VIEW.equals(intent.getAction())
4581                            && hasWebURI(intent))
4582                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4583            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4584                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4585            if (!allowMatchInstant) {
4586                flags &= ~PackageManager.MATCH_INSTANT;
4587            }
4588        }
4589        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4590    }
4591
4592    @Override
4593    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4594        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4595    }
4596
4597    /**
4598     * Important: The provided filterCallingUid is used exclusively to filter out activities
4599     * that can be seen based on user state. It's typically the original caller uid prior
4600     * to clearing. Because it can only be provided by trusted code, it's value can be
4601     * trusted and will be used as-is; unlike userId which will be validated by this method.
4602     */
4603    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4604            int filterCallingUid, int userId) {
4605        if (!sUserManager.exists(userId)) return null;
4606        flags = updateFlagsForComponent(flags, userId, component);
4607        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4608                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4609        synchronized (mPackages) {
4610            PackageParser.Activity a = mActivities.mActivities.get(component);
4611
4612            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4613            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4614                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4615                if (ps == null) return null;
4616                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4617                    return null;
4618                }
4619                return PackageParser.generateActivityInfo(
4620                        a, flags, ps.readUserState(userId), userId);
4621            }
4622            if (mResolveComponentName.equals(component)) {
4623                return PackageParser.generateActivityInfo(
4624                        mResolveActivity, flags, new PackageUserState(), userId);
4625            }
4626        }
4627        return null;
4628    }
4629
4630    @Override
4631    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4632            String resolvedType) {
4633        synchronized (mPackages) {
4634            if (component.equals(mResolveComponentName)) {
4635                // The resolver supports EVERYTHING!
4636                return true;
4637            }
4638            final int callingUid = Binder.getCallingUid();
4639            final int callingUserId = UserHandle.getUserId(callingUid);
4640            PackageParser.Activity a = mActivities.mActivities.get(component);
4641            if (a == null) {
4642                return false;
4643            }
4644            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4645            if (ps == null) {
4646                return false;
4647            }
4648            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4649                return false;
4650            }
4651            for (int i=0; i<a.intents.size(); i++) {
4652                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4653                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4654                    return true;
4655                }
4656            }
4657            return false;
4658        }
4659    }
4660
4661    @Override
4662    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4663        if (!sUserManager.exists(userId)) return null;
4664        final int callingUid = Binder.getCallingUid();
4665        flags = updateFlagsForComponent(flags, userId, component);
4666        enforceCrossUserPermission(callingUid, userId,
4667                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4668        synchronized (mPackages) {
4669            PackageParser.Activity a = mReceivers.mActivities.get(component);
4670            if (DEBUG_PACKAGE_INFO) Log.v(
4671                TAG, "getReceiverInfo " + component + ": " + a);
4672            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4673                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4674                if (ps == null) return null;
4675                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4676                    return null;
4677                }
4678                return PackageParser.generateActivityInfo(
4679                        a, flags, ps.readUserState(userId), userId);
4680            }
4681        }
4682        return null;
4683    }
4684
4685    @Override
4686    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4687            int flags, int userId) {
4688        if (!sUserManager.exists(userId)) return null;
4689        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4690        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4691            return null;
4692        }
4693
4694        flags = updateFlagsForPackage(flags, userId, null);
4695
4696        final boolean canSeeStaticLibraries =
4697                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4698                        == PERMISSION_GRANTED
4699                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4700                        == PERMISSION_GRANTED
4701                || canRequestPackageInstallsInternal(packageName,
4702                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4703                        false  /* throwIfPermNotDeclared*/)
4704                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4705                        == PERMISSION_GRANTED;
4706
4707        synchronized (mPackages) {
4708            List<SharedLibraryInfo> result = null;
4709
4710            final int libCount = mSharedLibraries.size();
4711            for (int i = 0; i < libCount; i++) {
4712                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4713                if (versionedLib == null) {
4714                    continue;
4715                }
4716
4717                final int versionCount = versionedLib.size();
4718                for (int j = 0; j < versionCount; j++) {
4719                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4720                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4721                        break;
4722                    }
4723                    final long identity = Binder.clearCallingIdentity();
4724                    try {
4725                        PackageInfo packageInfo = getPackageInfoVersioned(
4726                                libInfo.getDeclaringPackage(), flags
4727                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4728                        if (packageInfo == null) {
4729                            continue;
4730                        }
4731                    } finally {
4732                        Binder.restoreCallingIdentity(identity);
4733                    }
4734
4735                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4736                            libInfo.getVersion(), libInfo.getType(),
4737                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4738                            flags, userId));
4739
4740                    if (result == null) {
4741                        result = new ArrayList<>();
4742                    }
4743                    result.add(resLibInfo);
4744                }
4745            }
4746
4747            return result != null ? new ParceledListSlice<>(result) : null;
4748        }
4749    }
4750
4751    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4752            SharedLibraryInfo libInfo, int flags, int userId) {
4753        List<VersionedPackage> versionedPackages = null;
4754        final int packageCount = mSettings.mPackages.size();
4755        for (int i = 0; i < packageCount; i++) {
4756            PackageSetting ps = mSettings.mPackages.valueAt(i);
4757
4758            if (ps == null) {
4759                continue;
4760            }
4761
4762            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4763                continue;
4764            }
4765
4766            final String libName = libInfo.getName();
4767            if (libInfo.isStatic()) {
4768                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4769                if (libIdx < 0) {
4770                    continue;
4771                }
4772                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4773                    continue;
4774                }
4775                if (versionedPackages == null) {
4776                    versionedPackages = new ArrayList<>();
4777                }
4778                // If the dependent is a static shared lib, use the public package name
4779                String dependentPackageName = ps.name;
4780                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4781                    dependentPackageName = ps.pkg.manifestPackageName;
4782                }
4783                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4784            } else if (ps.pkg != null) {
4785                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4786                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4787                    if (versionedPackages == null) {
4788                        versionedPackages = new ArrayList<>();
4789                    }
4790                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4791                }
4792            }
4793        }
4794
4795        return versionedPackages;
4796    }
4797
4798    @Override
4799    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4800        if (!sUserManager.exists(userId)) return null;
4801        final int callingUid = Binder.getCallingUid();
4802        flags = updateFlagsForComponent(flags, userId, component);
4803        enforceCrossUserPermission(callingUid, userId,
4804                false /* requireFullPermission */, false /* checkShell */, "get service info");
4805        synchronized (mPackages) {
4806            PackageParser.Service s = mServices.mServices.get(component);
4807            if (DEBUG_PACKAGE_INFO) Log.v(
4808                TAG, "getServiceInfo " + component + ": " + s);
4809            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4810                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4811                if (ps == null) return null;
4812                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4813                    return null;
4814                }
4815                return PackageParser.generateServiceInfo(
4816                        s, flags, ps.readUserState(userId), userId);
4817            }
4818        }
4819        return null;
4820    }
4821
4822    @Override
4823    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4824        if (!sUserManager.exists(userId)) return null;
4825        final int callingUid = Binder.getCallingUid();
4826        flags = updateFlagsForComponent(flags, userId, component);
4827        enforceCrossUserPermission(callingUid, userId,
4828                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4829        synchronized (mPackages) {
4830            PackageParser.Provider p = mProviders.mProviders.get(component);
4831            if (DEBUG_PACKAGE_INFO) Log.v(
4832                TAG, "getProviderInfo " + component + ": " + p);
4833            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4834                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4835                if (ps == null) return null;
4836                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4837                    return null;
4838                }
4839                return PackageParser.generateProviderInfo(
4840                        p, flags, ps.readUserState(userId), userId);
4841            }
4842        }
4843        return null;
4844    }
4845
4846    @Override
4847    public String[] getSystemSharedLibraryNames() {
4848        // allow instant applications
4849        synchronized (mPackages) {
4850            Set<String> libs = null;
4851            final int libCount = mSharedLibraries.size();
4852            for (int i = 0; i < libCount; i++) {
4853                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4854                if (versionedLib == null) {
4855                    continue;
4856                }
4857                final int versionCount = versionedLib.size();
4858                for (int j = 0; j < versionCount; j++) {
4859                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4860                    if (!libEntry.info.isStatic()) {
4861                        if (libs == null) {
4862                            libs = new ArraySet<>();
4863                        }
4864                        libs.add(libEntry.info.getName());
4865                        break;
4866                    }
4867                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4868                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4869                            UserHandle.getUserId(Binder.getCallingUid()),
4870                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4871                        if (libs == null) {
4872                            libs = new ArraySet<>();
4873                        }
4874                        libs.add(libEntry.info.getName());
4875                        break;
4876                    }
4877                }
4878            }
4879
4880            if (libs != null) {
4881                String[] libsArray = new String[libs.size()];
4882                libs.toArray(libsArray);
4883                return libsArray;
4884            }
4885
4886            return null;
4887        }
4888    }
4889
4890    @Override
4891    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4892        // allow instant applications
4893        synchronized (mPackages) {
4894            return mServicesSystemSharedLibraryPackageName;
4895        }
4896    }
4897
4898    @Override
4899    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4900        // allow instant applications
4901        synchronized (mPackages) {
4902            return mSharedSystemSharedLibraryPackageName;
4903        }
4904    }
4905
4906    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4907        for (int i = userList.length - 1; i >= 0; --i) {
4908            final int userId = userList[i];
4909            // don't add instant app to the list of updates
4910            if (pkgSetting.getInstantApp(userId)) {
4911                continue;
4912            }
4913            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4914            if (changedPackages == null) {
4915                changedPackages = new SparseArray<>();
4916                mChangedPackages.put(userId, changedPackages);
4917            }
4918            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4919            if (sequenceNumbers == null) {
4920                sequenceNumbers = new HashMap<>();
4921                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4922            }
4923            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4924            if (sequenceNumber != null) {
4925                changedPackages.remove(sequenceNumber);
4926            }
4927            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4928            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4929        }
4930        mChangedPackagesSequenceNumber++;
4931    }
4932
4933    @Override
4934    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4935        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4936            return null;
4937        }
4938        synchronized (mPackages) {
4939            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4940                return null;
4941            }
4942            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4943            if (changedPackages == null) {
4944                return null;
4945            }
4946            final List<String> packageNames =
4947                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4948            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4949                final String packageName = changedPackages.get(i);
4950                if (packageName != null) {
4951                    packageNames.add(packageName);
4952                }
4953            }
4954            return packageNames.isEmpty()
4955                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4956        }
4957    }
4958
4959    @Override
4960    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4961        // allow instant applications
4962        ArrayList<FeatureInfo> res;
4963        synchronized (mAvailableFeatures) {
4964            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4965            res.addAll(mAvailableFeatures.values());
4966        }
4967        final FeatureInfo fi = new FeatureInfo();
4968        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4969                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4970        res.add(fi);
4971
4972        return new ParceledListSlice<>(res);
4973    }
4974
4975    @Override
4976    public boolean hasSystemFeature(String name, int version) {
4977        // allow instant applications
4978        synchronized (mAvailableFeatures) {
4979            final FeatureInfo feat = mAvailableFeatures.get(name);
4980            if (feat == null) {
4981                return false;
4982            } else {
4983                return feat.version >= version;
4984            }
4985        }
4986    }
4987
4988    @Override
4989    public int checkPermission(String permName, String pkgName, int userId) {
4990        if (!sUserManager.exists(userId)) {
4991            return PackageManager.PERMISSION_DENIED;
4992        }
4993        final int callingUid = Binder.getCallingUid();
4994
4995        synchronized (mPackages) {
4996            final PackageParser.Package p = mPackages.get(pkgName);
4997            if (p != null && p.mExtras != null) {
4998                final PackageSetting ps = (PackageSetting) p.mExtras;
4999                if (filterAppAccessLPr(ps, callingUid, userId)) {
5000                    return PackageManager.PERMISSION_DENIED;
5001                }
5002                final boolean instantApp = ps.getInstantApp(userId);
5003                final PermissionsState permissionsState = ps.getPermissionsState();
5004                if (permissionsState.hasPermission(permName, userId)) {
5005                    if (instantApp) {
5006                        BasePermission bp = mSettings.mPermissions.get(permName);
5007                        if (bp != null && bp.isInstant()) {
5008                            return PackageManager.PERMISSION_GRANTED;
5009                        }
5010                    } else {
5011                        return PackageManager.PERMISSION_GRANTED;
5012                    }
5013                }
5014                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5015                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5016                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5017                    return PackageManager.PERMISSION_GRANTED;
5018                }
5019            }
5020        }
5021
5022        return PackageManager.PERMISSION_DENIED;
5023    }
5024
5025    @Override
5026    public int checkUidPermission(String permName, int uid) {
5027        final int callingUid = Binder.getCallingUid();
5028        final int callingUserId = UserHandle.getUserId(callingUid);
5029        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5030        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5031        final int userId = UserHandle.getUserId(uid);
5032        if (!sUserManager.exists(userId)) {
5033            return PackageManager.PERMISSION_DENIED;
5034        }
5035
5036        synchronized (mPackages) {
5037            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5038            if (obj != null) {
5039                if (obj instanceof SharedUserSetting) {
5040                    if (isCallerInstantApp) {
5041                        return PackageManager.PERMISSION_DENIED;
5042                    }
5043                } else if (obj instanceof PackageSetting) {
5044                    final PackageSetting ps = (PackageSetting) obj;
5045                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5046                        return PackageManager.PERMISSION_DENIED;
5047                    }
5048                }
5049                final SettingBase settingBase = (SettingBase) obj;
5050                final PermissionsState permissionsState = settingBase.getPermissionsState();
5051                if (permissionsState.hasPermission(permName, userId)) {
5052                    if (isUidInstantApp) {
5053                        BasePermission bp = mSettings.mPermissions.get(permName);
5054                        if (bp != null && bp.isInstant()) {
5055                            return PackageManager.PERMISSION_GRANTED;
5056                        }
5057                    } else {
5058                        return PackageManager.PERMISSION_GRANTED;
5059                    }
5060                }
5061                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5062                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5063                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5064                    return PackageManager.PERMISSION_GRANTED;
5065                }
5066            } else {
5067                ArraySet<String> perms = mSystemPermissions.get(uid);
5068                if (perms != null) {
5069                    if (perms.contains(permName)) {
5070                        return PackageManager.PERMISSION_GRANTED;
5071                    }
5072                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5073                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5074                        return PackageManager.PERMISSION_GRANTED;
5075                    }
5076                }
5077            }
5078        }
5079
5080        return PackageManager.PERMISSION_DENIED;
5081    }
5082
5083    @Override
5084    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5085        if (UserHandle.getCallingUserId() != userId) {
5086            mContext.enforceCallingPermission(
5087                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5088                    "isPermissionRevokedByPolicy for user " + userId);
5089        }
5090
5091        if (checkPermission(permission, packageName, userId)
5092                == PackageManager.PERMISSION_GRANTED) {
5093            return false;
5094        }
5095
5096        final int callingUid = Binder.getCallingUid();
5097        if (getInstantAppPackageName(callingUid) != null) {
5098            if (!isCallerSameApp(packageName, callingUid)) {
5099                return false;
5100            }
5101        } else {
5102            if (isInstantApp(packageName, userId)) {
5103                return false;
5104            }
5105        }
5106
5107        final long identity = Binder.clearCallingIdentity();
5108        try {
5109            final int flags = getPermissionFlags(permission, packageName, userId);
5110            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5111        } finally {
5112            Binder.restoreCallingIdentity(identity);
5113        }
5114    }
5115
5116    @Override
5117    public String getPermissionControllerPackageName() {
5118        synchronized (mPackages) {
5119            return mRequiredInstallerPackage;
5120        }
5121    }
5122
5123    /**
5124     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5125     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5126     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5127     * @param message the message to log on security exception
5128     */
5129    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5130            boolean checkShell, String message) {
5131        if (userId < 0) {
5132            throw new IllegalArgumentException("Invalid userId " + userId);
5133        }
5134        if (checkShell) {
5135            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5136        }
5137        if (userId == UserHandle.getUserId(callingUid)) return;
5138        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5139            if (requireFullPermission) {
5140                mContext.enforceCallingOrSelfPermission(
5141                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5142            } else {
5143                try {
5144                    mContext.enforceCallingOrSelfPermission(
5145                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5146                } catch (SecurityException se) {
5147                    mContext.enforceCallingOrSelfPermission(
5148                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5149                }
5150            }
5151        }
5152    }
5153
5154    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5155        if (callingUid == Process.SHELL_UID) {
5156            if (userHandle >= 0
5157                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5158                throw new SecurityException("Shell does not have permission to access user "
5159                        + userHandle);
5160            } else if (userHandle < 0) {
5161                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5162                        + Debug.getCallers(3));
5163            }
5164        }
5165    }
5166
5167    private BasePermission findPermissionTreeLP(String permName) {
5168        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5169            if (permName.startsWith(bp.name) &&
5170                    permName.length() > bp.name.length() &&
5171                    permName.charAt(bp.name.length()) == '.') {
5172                return bp;
5173            }
5174        }
5175        return null;
5176    }
5177
5178    private BasePermission checkPermissionTreeLP(String permName) {
5179        if (permName != null) {
5180            BasePermission bp = findPermissionTreeLP(permName);
5181            if (bp != null) {
5182                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5183                    return bp;
5184                }
5185                throw new SecurityException("Calling uid "
5186                        + Binder.getCallingUid()
5187                        + " is not allowed to add to permission tree "
5188                        + bp.name + " owned by uid " + bp.uid);
5189            }
5190        }
5191        throw new SecurityException("No permission tree found for " + permName);
5192    }
5193
5194    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5195        if (s1 == null) {
5196            return s2 == null;
5197        }
5198        if (s2 == null) {
5199            return false;
5200        }
5201        if (s1.getClass() != s2.getClass()) {
5202            return false;
5203        }
5204        return s1.equals(s2);
5205    }
5206
5207    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5208        if (pi1.icon != pi2.icon) return false;
5209        if (pi1.logo != pi2.logo) return false;
5210        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5211        if (!compareStrings(pi1.name, pi2.name)) return false;
5212        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5213        // We'll take care of setting this one.
5214        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5215        // These are not currently stored in settings.
5216        //if (!compareStrings(pi1.group, pi2.group)) return false;
5217        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5218        //if (pi1.labelRes != pi2.labelRes) return false;
5219        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5220        return true;
5221    }
5222
5223    int permissionInfoFootprint(PermissionInfo info) {
5224        int size = info.name.length();
5225        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5226        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5227        return size;
5228    }
5229
5230    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5231        int size = 0;
5232        for (BasePermission perm : mSettings.mPermissions.values()) {
5233            if (perm.uid == tree.uid) {
5234                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5235            }
5236        }
5237        return size;
5238    }
5239
5240    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5241        // We calculate the max size of permissions defined by this uid and throw
5242        // if that plus the size of 'info' would exceed our stated maximum.
5243        if (tree.uid != Process.SYSTEM_UID) {
5244            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5245            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5246                throw new SecurityException("Permission tree size cap exceeded");
5247            }
5248        }
5249    }
5250
5251    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5252        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5253            throw new SecurityException("Instant apps can't add permissions");
5254        }
5255        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5256            throw new SecurityException("Label must be specified in permission");
5257        }
5258        BasePermission tree = checkPermissionTreeLP(info.name);
5259        BasePermission bp = mSettings.mPermissions.get(info.name);
5260        boolean added = bp == null;
5261        boolean changed = true;
5262        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5263        if (added) {
5264            enforcePermissionCapLocked(info, tree);
5265            bp = new BasePermission(info.name, tree.sourcePackage,
5266                    BasePermission.TYPE_DYNAMIC);
5267        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5268            throw new SecurityException(
5269                    "Not allowed to modify non-dynamic permission "
5270                    + info.name);
5271        } else {
5272            if (bp.protectionLevel == fixedLevel
5273                    && bp.perm.owner.equals(tree.perm.owner)
5274                    && bp.uid == tree.uid
5275                    && comparePermissionInfos(bp.perm.info, info)) {
5276                changed = false;
5277            }
5278        }
5279        bp.protectionLevel = fixedLevel;
5280        info = new PermissionInfo(info);
5281        info.protectionLevel = fixedLevel;
5282        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5283        bp.perm.info.packageName = tree.perm.info.packageName;
5284        bp.uid = tree.uid;
5285        if (added) {
5286            mSettings.mPermissions.put(info.name, bp);
5287        }
5288        if (changed) {
5289            if (!async) {
5290                mSettings.writeLPr();
5291            } else {
5292                scheduleWriteSettingsLocked();
5293            }
5294        }
5295        return added;
5296    }
5297
5298    @Override
5299    public boolean addPermission(PermissionInfo info) {
5300        synchronized (mPackages) {
5301            return addPermissionLocked(info, false);
5302        }
5303    }
5304
5305    @Override
5306    public boolean addPermissionAsync(PermissionInfo info) {
5307        synchronized (mPackages) {
5308            return addPermissionLocked(info, true);
5309        }
5310    }
5311
5312    @Override
5313    public void removePermission(String name) {
5314        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5315            throw new SecurityException("Instant applications don't have access to this method");
5316        }
5317        synchronized (mPackages) {
5318            checkPermissionTreeLP(name);
5319            BasePermission bp = mSettings.mPermissions.get(name);
5320            if (bp != null) {
5321                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5322                    throw new SecurityException(
5323                            "Not allowed to modify non-dynamic permission "
5324                            + name);
5325                }
5326                mSettings.mPermissions.remove(name);
5327                mSettings.writeLPr();
5328            }
5329        }
5330    }
5331
5332    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5333            PackageParser.Package pkg, BasePermission bp) {
5334        int index = pkg.requestedPermissions.indexOf(bp.name);
5335        if (index == -1) {
5336            throw new SecurityException("Package " + pkg.packageName
5337                    + " has not requested permission " + bp.name);
5338        }
5339        if (!bp.isRuntime() && !bp.isDevelopment()) {
5340            throw new SecurityException("Permission " + bp.name
5341                    + " is not a changeable permission type");
5342        }
5343    }
5344
5345    @Override
5346    public void grantRuntimePermission(String packageName, String name, final int userId) {
5347        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5348    }
5349
5350    private void grantRuntimePermission(String packageName, String name, final int userId,
5351            boolean overridePolicy) {
5352        if (!sUserManager.exists(userId)) {
5353            Log.e(TAG, "No such user:" + userId);
5354            return;
5355        }
5356        final int callingUid = Binder.getCallingUid();
5357
5358        mContext.enforceCallingOrSelfPermission(
5359                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5360                "grantRuntimePermission");
5361
5362        enforceCrossUserPermission(callingUid, userId,
5363                true /* requireFullPermission */, true /* checkShell */,
5364                "grantRuntimePermission");
5365
5366        final int uid;
5367        final PackageSetting ps;
5368
5369        synchronized (mPackages) {
5370            final PackageParser.Package pkg = mPackages.get(packageName);
5371            if (pkg == null) {
5372                throw new IllegalArgumentException("Unknown package: " + packageName);
5373            }
5374            final BasePermission bp = mSettings.mPermissions.get(name);
5375            if (bp == null) {
5376                throw new IllegalArgumentException("Unknown permission: " + name);
5377            }
5378            ps = (PackageSetting) pkg.mExtras;
5379            if (ps == null
5380                    || filterAppAccessLPr(ps, callingUid, userId)) {
5381                throw new IllegalArgumentException("Unknown package: " + packageName);
5382            }
5383
5384            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5385
5386            // If a permission review is required for legacy apps we represent
5387            // their permissions as always granted runtime ones since we need
5388            // to keep the review required permission flag per user while an
5389            // install permission's state is shared across all users.
5390            if (mPermissionReviewRequired
5391                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5392                    && bp.isRuntime()) {
5393                return;
5394            }
5395
5396            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5397
5398            final PermissionsState permissionsState = ps.getPermissionsState();
5399
5400            final int flags = permissionsState.getPermissionFlags(name, userId);
5401            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5402                throw new SecurityException("Cannot grant system fixed permission "
5403                        + name + " for package " + packageName);
5404            }
5405            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5406                throw new SecurityException("Cannot grant policy fixed permission "
5407                        + name + " for package " + packageName);
5408            }
5409
5410            if (bp.isDevelopment()) {
5411                // Development permissions must be handled specially, since they are not
5412                // normal runtime permissions.  For now they apply to all users.
5413                if (permissionsState.grantInstallPermission(bp) !=
5414                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5415                    scheduleWriteSettingsLocked();
5416                }
5417                return;
5418            }
5419
5420            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5421                throw new SecurityException("Cannot grant non-ephemeral permission"
5422                        + name + " for package " + packageName);
5423            }
5424
5425            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5426                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5427                return;
5428            }
5429
5430            final int result = permissionsState.grantRuntimePermission(bp, userId);
5431            switch (result) {
5432                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5433                    return;
5434                }
5435
5436                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5437                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5438                    mHandler.post(new Runnable() {
5439                        @Override
5440                        public void run() {
5441                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5442                        }
5443                    });
5444                }
5445                break;
5446            }
5447
5448            if (bp.isRuntime()) {
5449                logPermissionGranted(mContext, name, packageName);
5450            }
5451
5452            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5453
5454            // Not critical if that is lost - app has to request again.
5455            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5456        }
5457
5458        // Only need to do this if user is initialized. Otherwise it's a new user
5459        // and there are no processes running as the user yet and there's no need
5460        // to make an expensive call to remount processes for the changed permissions.
5461        if (READ_EXTERNAL_STORAGE.equals(name)
5462                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5463            final long token = Binder.clearCallingIdentity();
5464            try {
5465                if (sUserManager.isInitialized(userId)) {
5466                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5467                            StorageManagerInternal.class);
5468                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5469                }
5470            } finally {
5471                Binder.restoreCallingIdentity(token);
5472            }
5473        }
5474    }
5475
5476    @Override
5477    public void revokeRuntimePermission(String packageName, String name, int userId) {
5478        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5479    }
5480
5481    private void revokeRuntimePermission(String packageName, String name, int userId,
5482            boolean overridePolicy) {
5483        if (!sUserManager.exists(userId)) {
5484            Log.e(TAG, "No such user:" + userId);
5485            return;
5486        }
5487
5488        mContext.enforceCallingOrSelfPermission(
5489                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5490                "revokeRuntimePermission");
5491
5492        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5493                true /* requireFullPermission */, true /* checkShell */,
5494                "revokeRuntimePermission");
5495
5496        final int appId;
5497
5498        synchronized (mPackages) {
5499            final PackageParser.Package pkg = mPackages.get(packageName);
5500            if (pkg == null) {
5501                throw new IllegalArgumentException("Unknown package: " + packageName);
5502            }
5503            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5504            if (ps == null
5505                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5506                throw new IllegalArgumentException("Unknown package: " + packageName);
5507            }
5508            final BasePermission bp = mSettings.mPermissions.get(name);
5509            if (bp == null) {
5510                throw new IllegalArgumentException("Unknown permission: " + name);
5511            }
5512
5513            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5514
5515            // If a permission review is required for legacy apps we represent
5516            // their permissions as always granted runtime ones since we need
5517            // to keep the review required permission flag per user while an
5518            // install permission's state is shared across all users.
5519            if (mPermissionReviewRequired
5520                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5521                    && bp.isRuntime()) {
5522                return;
5523            }
5524
5525            final PermissionsState permissionsState = ps.getPermissionsState();
5526
5527            final int flags = permissionsState.getPermissionFlags(name, userId);
5528            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5529                throw new SecurityException("Cannot revoke system fixed permission "
5530                        + name + " for package " + packageName);
5531            }
5532            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5533                throw new SecurityException("Cannot revoke policy fixed permission "
5534                        + name + " for package " + packageName);
5535            }
5536
5537            if (bp.isDevelopment()) {
5538                // Development permissions must be handled specially, since they are not
5539                // normal runtime permissions.  For now they apply to all users.
5540                if (permissionsState.revokeInstallPermission(bp) !=
5541                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5542                    scheduleWriteSettingsLocked();
5543                }
5544                return;
5545            }
5546
5547            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5548                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5549                return;
5550            }
5551
5552            if (bp.isRuntime()) {
5553                logPermissionRevoked(mContext, name, packageName);
5554            }
5555
5556            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5557
5558            // Critical, after this call app should never have the permission.
5559            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5560
5561            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5562        }
5563
5564        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5565    }
5566
5567    /**
5568     * Get the first event id for the permission.
5569     *
5570     * <p>There are four events for each permission: <ul>
5571     *     <li>Request permission: first id + 0</li>
5572     *     <li>Grant permission: first id + 1</li>
5573     *     <li>Request for permission denied: first id + 2</li>
5574     *     <li>Revoke permission: first id + 3</li>
5575     * </ul></p>
5576     *
5577     * @param name name of the permission
5578     *
5579     * @return The first event id for the permission
5580     */
5581    private static int getBaseEventId(@NonNull String name) {
5582        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5583
5584        if (eventIdIndex == -1) {
5585            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5586                    || "user".equals(Build.TYPE)) {
5587                Log.i(TAG, "Unknown permission " + name);
5588
5589                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5590            } else {
5591                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5592                //
5593                // Also update
5594                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5595                // - metrics_constants.proto
5596                throw new IllegalStateException("Unknown permission " + name);
5597            }
5598        }
5599
5600        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5601    }
5602
5603    /**
5604     * Log that a permission was revoked.
5605     *
5606     * @param context Context of the caller
5607     * @param name name of the permission
5608     * @param packageName package permission if for
5609     */
5610    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5611            @NonNull String packageName) {
5612        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5613    }
5614
5615    /**
5616     * Log that a permission request was granted.
5617     *
5618     * @param context Context of the caller
5619     * @param name name of the permission
5620     * @param packageName package permission if for
5621     */
5622    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5623            @NonNull String packageName) {
5624        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5625    }
5626
5627    @Override
5628    public void resetRuntimePermissions() {
5629        mContext.enforceCallingOrSelfPermission(
5630                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5631                "revokeRuntimePermission");
5632
5633        int callingUid = Binder.getCallingUid();
5634        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5635            mContext.enforceCallingOrSelfPermission(
5636                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5637                    "resetRuntimePermissions");
5638        }
5639
5640        synchronized (mPackages) {
5641            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5642            for (int userId : UserManagerService.getInstance().getUserIds()) {
5643                final int packageCount = mPackages.size();
5644                for (int i = 0; i < packageCount; i++) {
5645                    PackageParser.Package pkg = mPackages.valueAt(i);
5646                    if (!(pkg.mExtras instanceof PackageSetting)) {
5647                        continue;
5648                    }
5649                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5650                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5651                }
5652            }
5653        }
5654    }
5655
5656    @Override
5657    public int getPermissionFlags(String name, String packageName, int userId) {
5658        if (!sUserManager.exists(userId)) {
5659            return 0;
5660        }
5661
5662        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5663
5664        final int callingUid = Binder.getCallingUid();
5665        enforceCrossUserPermission(callingUid, userId,
5666                true /* requireFullPermission */, false /* checkShell */,
5667                "getPermissionFlags");
5668
5669        synchronized (mPackages) {
5670            final PackageParser.Package pkg = mPackages.get(packageName);
5671            if (pkg == null) {
5672                return 0;
5673            }
5674            final BasePermission bp = mSettings.mPermissions.get(name);
5675            if (bp == null) {
5676                return 0;
5677            }
5678            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5679            if (ps == null
5680                    || filterAppAccessLPr(ps, callingUid, userId)) {
5681                return 0;
5682            }
5683            PermissionsState permissionsState = ps.getPermissionsState();
5684            return permissionsState.getPermissionFlags(name, userId);
5685        }
5686    }
5687
5688    @Override
5689    public void updatePermissionFlags(String name, String packageName, int flagMask,
5690            int flagValues, int userId) {
5691        if (!sUserManager.exists(userId)) {
5692            return;
5693        }
5694
5695        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5696
5697        final int callingUid = Binder.getCallingUid();
5698        enforceCrossUserPermission(callingUid, userId,
5699                true /* requireFullPermission */, true /* checkShell */,
5700                "updatePermissionFlags");
5701
5702        // Only the system can change these flags and nothing else.
5703        if (getCallingUid() != Process.SYSTEM_UID) {
5704            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5705            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5706            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5707            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5708            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5709        }
5710
5711        synchronized (mPackages) {
5712            final PackageParser.Package pkg = mPackages.get(packageName);
5713            if (pkg == null) {
5714                throw new IllegalArgumentException("Unknown package: " + packageName);
5715            }
5716            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5717            if (ps == null
5718                    || filterAppAccessLPr(ps, callingUid, userId)) {
5719                throw new IllegalArgumentException("Unknown package: " + packageName);
5720            }
5721
5722            final BasePermission bp = mSettings.mPermissions.get(name);
5723            if (bp == null) {
5724                throw new IllegalArgumentException("Unknown permission: " + name);
5725            }
5726
5727            PermissionsState permissionsState = ps.getPermissionsState();
5728
5729            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5730
5731            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5732                // Install and runtime permissions are stored in different places,
5733                // so figure out what permission changed and persist the change.
5734                if (permissionsState.getInstallPermissionState(name) != null) {
5735                    scheduleWriteSettingsLocked();
5736                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5737                        || hadState) {
5738                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5739                }
5740            }
5741        }
5742    }
5743
5744    /**
5745     * Update the permission flags for all packages and runtime permissions of a user in order
5746     * to allow device or profile owner to remove POLICY_FIXED.
5747     */
5748    @Override
5749    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5750        if (!sUserManager.exists(userId)) {
5751            return;
5752        }
5753
5754        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5755
5756        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5757                true /* requireFullPermission */, true /* checkShell */,
5758                "updatePermissionFlagsForAllApps");
5759
5760        // Only the system can change system fixed flags.
5761        if (getCallingUid() != Process.SYSTEM_UID) {
5762            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5763            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5764        }
5765
5766        synchronized (mPackages) {
5767            boolean changed = false;
5768            final int packageCount = mPackages.size();
5769            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5770                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5771                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5772                if (ps == null) {
5773                    continue;
5774                }
5775                PermissionsState permissionsState = ps.getPermissionsState();
5776                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5777                        userId, flagMask, flagValues);
5778            }
5779            if (changed) {
5780                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5781            }
5782        }
5783    }
5784
5785    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5786        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5787                != PackageManager.PERMISSION_GRANTED
5788            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5789                != PackageManager.PERMISSION_GRANTED) {
5790            throw new SecurityException(message + " requires "
5791                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5792                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5793        }
5794    }
5795
5796    @Override
5797    public boolean shouldShowRequestPermissionRationale(String permissionName,
5798            String packageName, int userId) {
5799        if (UserHandle.getCallingUserId() != userId) {
5800            mContext.enforceCallingPermission(
5801                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5802                    "canShowRequestPermissionRationale for user " + userId);
5803        }
5804
5805        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5806        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5807            return false;
5808        }
5809
5810        if (checkPermission(permissionName, packageName, userId)
5811                == PackageManager.PERMISSION_GRANTED) {
5812            return false;
5813        }
5814
5815        final int flags;
5816
5817        final long identity = Binder.clearCallingIdentity();
5818        try {
5819            flags = getPermissionFlags(permissionName,
5820                    packageName, userId);
5821        } finally {
5822            Binder.restoreCallingIdentity(identity);
5823        }
5824
5825        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5826                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5827                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5828
5829        if ((flags & fixedFlags) != 0) {
5830            return false;
5831        }
5832
5833        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5834    }
5835
5836    @Override
5837    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5838        mContext.enforceCallingOrSelfPermission(
5839                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5840                "addOnPermissionsChangeListener");
5841
5842        synchronized (mPackages) {
5843            mOnPermissionChangeListeners.addListenerLocked(listener);
5844        }
5845    }
5846
5847    @Override
5848    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5849        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5850            throw new SecurityException("Instant applications don't have access to this method");
5851        }
5852        synchronized (mPackages) {
5853            mOnPermissionChangeListeners.removeListenerLocked(listener);
5854        }
5855    }
5856
5857    @Override
5858    public boolean isProtectedBroadcast(String actionName) {
5859        // allow instant applications
5860        synchronized (mPackages) {
5861            if (mProtectedBroadcasts.contains(actionName)) {
5862                return true;
5863            } else if (actionName != null) {
5864                // TODO: remove these terrible hacks
5865                if (actionName.startsWith("android.net.netmon.lingerExpired")
5866                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5867                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5868                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5869                    return true;
5870                }
5871            }
5872        }
5873        return false;
5874    }
5875
5876    @Override
5877    public int checkSignatures(String pkg1, String pkg2) {
5878        synchronized (mPackages) {
5879            final PackageParser.Package p1 = mPackages.get(pkg1);
5880            final PackageParser.Package p2 = mPackages.get(pkg2);
5881            if (p1 == null || p1.mExtras == null
5882                    || p2 == null || p2.mExtras == null) {
5883                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5884            }
5885            final int callingUid = Binder.getCallingUid();
5886            final int callingUserId = UserHandle.getUserId(callingUid);
5887            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5888            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5889            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5890                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5891                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5892            }
5893            return compareSignatures(p1.mSignatures, p2.mSignatures);
5894        }
5895    }
5896
5897    @Override
5898    public int checkUidSignatures(int uid1, int uid2) {
5899        final int callingUid = Binder.getCallingUid();
5900        final int callingUserId = UserHandle.getUserId(callingUid);
5901        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5902        // Map to base uids.
5903        uid1 = UserHandle.getAppId(uid1);
5904        uid2 = UserHandle.getAppId(uid2);
5905        // reader
5906        synchronized (mPackages) {
5907            Signature[] s1;
5908            Signature[] s2;
5909            Object obj = mSettings.getUserIdLPr(uid1);
5910            if (obj != null) {
5911                if (obj instanceof SharedUserSetting) {
5912                    if (isCallerInstantApp) {
5913                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5914                    }
5915                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5916                } else if (obj instanceof PackageSetting) {
5917                    final PackageSetting ps = (PackageSetting) obj;
5918                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5919                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5920                    }
5921                    s1 = ps.signatures.mSignatures;
5922                } else {
5923                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5924                }
5925            } else {
5926                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5927            }
5928            obj = mSettings.getUserIdLPr(uid2);
5929            if (obj != null) {
5930                if (obj instanceof SharedUserSetting) {
5931                    if (isCallerInstantApp) {
5932                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5933                    }
5934                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5935                } else if (obj instanceof PackageSetting) {
5936                    final PackageSetting ps = (PackageSetting) obj;
5937                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5938                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5939                    }
5940                    s2 = ps.signatures.mSignatures;
5941                } else {
5942                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5943                }
5944            } else {
5945                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5946            }
5947            return compareSignatures(s1, s2);
5948        }
5949    }
5950
5951    /**
5952     * This method should typically only be used when granting or revoking
5953     * permissions, since the app may immediately restart after this call.
5954     * <p>
5955     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5956     * guard your work against the app being relaunched.
5957     */
5958    private void killUid(int appId, int userId, String reason) {
5959        final long identity = Binder.clearCallingIdentity();
5960        try {
5961            IActivityManager am = ActivityManager.getService();
5962            if (am != null) {
5963                try {
5964                    am.killUid(appId, userId, reason);
5965                } catch (RemoteException e) {
5966                    /* ignore - same process */
5967                }
5968            }
5969        } finally {
5970            Binder.restoreCallingIdentity(identity);
5971        }
5972    }
5973
5974    /**
5975     * Compares two sets of signatures. Returns:
5976     * <br />
5977     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5978     * <br />
5979     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5980     * <br />
5981     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5982     * <br />
5983     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5984     * <br />
5985     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5986     */
5987    static int compareSignatures(Signature[] s1, Signature[] s2) {
5988        if (s1 == null) {
5989            return s2 == null
5990                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5991                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5992        }
5993
5994        if (s2 == null) {
5995            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5996        }
5997
5998        if (s1.length != s2.length) {
5999            return PackageManager.SIGNATURE_NO_MATCH;
6000        }
6001
6002        // Since both signature sets are of size 1, we can compare without HashSets.
6003        if (s1.length == 1) {
6004            return s1[0].equals(s2[0]) ?
6005                    PackageManager.SIGNATURE_MATCH :
6006                    PackageManager.SIGNATURE_NO_MATCH;
6007        }
6008
6009        ArraySet<Signature> set1 = new ArraySet<Signature>();
6010        for (Signature sig : s1) {
6011            set1.add(sig);
6012        }
6013        ArraySet<Signature> set2 = new ArraySet<Signature>();
6014        for (Signature sig : s2) {
6015            set2.add(sig);
6016        }
6017        // Make sure s2 contains all signatures in s1.
6018        if (set1.equals(set2)) {
6019            return PackageManager.SIGNATURE_MATCH;
6020        }
6021        return PackageManager.SIGNATURE_NO_MATCH;
6022    }
6023
6024    /**
6025     * If the database version for this type of package (internal storage or
6026     * external storage) is less than the version where package signatures
6027     * were updated, return true.
6028     */
6029    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6030        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6031        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6032    }
6033
6034    /**
6035     * Used for backward compatibility to make sure any packages with
6036     * certificate chains get upgraded to the new style. {@code existingSigs}
6037     * will be in the old format (since they were stored on disk from before the
6038     * system upgrade) and {@code scannedSigs} will be in the newer format.
6039     */
6040    private int compareSignaturesCompat(PackageSignatures existingSigs,
6041            PackageParser.Package scannedPkg) {
6042        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6043            return PackageManager.SIGNATURE_NO_MATCH;
6044        }
6045
6046        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6047        for (Signature sig : existingSigs.mSignatures) {
6048            existingSet.add(sig);
6049        }
6050        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6051        for (Signature sig : scannedPkg.mSignatures) {
6052            try {
6053                Signature[] chainSignatures = sig.getChainSignatures();
6054                for (Signature chainSig : chainSignatures) {
6055                    scannedCompatSet.add(chainSig);
6056                }
6057            } catch (CertificateEncodingException e) {
6058                scannedCompatSet.add(sig);
6059            }
6060        }
6061        /*
6062         * Make sure the expanded scanned set contains all signatures in the
6063         * existing one.
6064         */
6065        if (scannedCompatSet.equals(existingSet)) {
6066            // Migrate the old signatures to the new scheme.
6067            existingSigs.assignSignatures(scannedPkg.mSignatures);
6068            // The new KeySets will be re-added later in the scanning process.
6069            synchronized (mPackages) {
6070                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6071            }
6072            return PackageManager.SIGNATURE_MATCH;
6073        }
6074        return PackageManager.SIGNATURE_NO_MATCH;
6075    }
6076
6077    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6078        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6079        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6080    }
6081
6082    private int compareSignaturesRecover(PackageSignatures existingSigs,
6083            PackageParser.Package scannedPkg) {
6084        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6085            return PackageManager.SIGNATURE_NO_MATCH;
6086        }
6087
6088        String msg = null;
6089        try {
6090            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6091                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6092                        + scannedPkg.packageName);
6093                return PackageManager.SIGNATURE_MATCH;
6094            }
6095        } catch (CertificateException e) {
6096            msg = e.getMessage();
6097        }
6098
6099        logCriticalInfo(Log.INFO,
6100                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6101        return PackageManager.SIGNATURE_NO_MATCH;
6102    }
6103
6104    @Override
6105    public List<String> getAllPackages() {
6106        final int callingUid = Binder.getCallingUid();
6107        final int callingUserId = UserHandle.getUserId(callingUid);
6108        synchronized (mPackages) {
6109            if (canViewInstantApps(callingUid, callingUserId)) {
6110                return new ArrayList<String>(mPackages.keySet());
6111            }
6112            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6113            final List<String> result = new ArrayList<>();
6114            if (instantAppPkgName != null) {
6115                // caller is an instant application; filter unexposed applications
6116                for (PackageParser.Package pkg : mPackages.values()) {
6117                    if (!pkg.visibleToInstantApps) {
6118                        continue;
6119                    }
6120                    result.add(pkg.packageName);
6121                }
6122            } else {
6123                // caller is a normal application; filter instant applications
6124                for (PackageParser.Package pkg : mPackages.values()) {
6125                    final PackageSetting ps =
6126                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6127                    if (ps != null
6128                            && ps.getInstantApp(callingUserId)
6129                            && !mInstantAppRegistry.isInstantAccessGranted(
6130                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6131                        continue;
6132                    }
6133                    result.add(pkg.packageName);
6134                }
6135            }
6136            return result;
6137        }
6138    }
6139
6140    @Override
6141    public String[] getPackagesForUid(int uid) {
6142        final int callingUid = Binder.getCallingUid();
6143        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6144        final int userId = UserHandle.getUserId(uid);
6145        uid = UserHandle.getAppId(uid);
6146        // reader
6147        synchronized (mPackages) {
6148            Object obj = mSettings.getUserIdLPr(uid);
6149            if (obj instanceof SharedUserSetting) {
6150                if (isCallerInstantApp) {
6151                    return null;
6152                }
6153                final SharedUserSetting sus = (SharedUserSetting) obj;
6154                final int N = sus.packages.size();
6155                String[] res = new String[N];
6156                final Iterator<PackageSetting> it = sus.packages.iterator();
6157                int i = 0;
6158                while (it.hasNext()) {
6159                    PackageSetting ps = it.next();
6160                    if (ps.getInstalled(userId)) {
6161                        res[i++] = ps.name;
6162                    } else {
6163                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6164                    }
6165                }
6166                return res;
6167            } else if (obj instanceof PackageSetting) {
6168                final PackageSetting ps = (PackageSetting) obj;
6169                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6170                    return new String[]{ps.name};
6171                }
6172            }
6173        }
6174        return null;
6175    }
6176
6177    @Override
6178    public String getNameForUid(int uid) {
6179        final int callingUid = Binder.getCallingUid();
6180        if (getInstantAppPackageName(callingUid) != null) {
6181            return null;
6182        }
6183        synchronized (mPackages) {
6184            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6185            if (obj instanceof SharedUserSetting) {
6186                final SharedUserSetting sus = (SharedUserSetting) obj;
6187                return sus.name + ":" + sus.userId;
6188            } else if (obj instanceof PackageSetting) {
6189                final PackageSetting ps = (PackageSetting) obj;
6190                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6191                    return null;
6192                }
6193                return ps.name;
6194            }
6195        }
6196        return null;
6197    }
6198
6199    @Override
6200    public int getUidForSharedUser(String sharedUserName) {
6201        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6202            return -1;
6203        }
6204        if (sharedUserName == null) {
6205            return -1;
6206        }
6207        // reader
6208        synchronized (mPackages) {
6209            SharedUserSetting suid;
6210            try {
6211                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6212                if (suid != null) {
6213                    return suid.userId;
6214                }
6215            } catch (PackageManagerException ignore) {
6216                // can't happen, but, still need to catch it
6217            }
6218            return -1;
6219        }
6220    }
6221
6222    @Override
6223    public int getFlagsForUid(int uid) {
6224        final int callingUid = Binder.getCallingUid();
6225        if (getInstantAppPackageName(callingUid) != null) {
6226            return 0;
6227        }
6228        synchronized (mPackages) {
6229            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6230            if (obj instanceof SharedUserSetting) {
6231                final SharedUserSetting sus = (SharedUserSetting) obj;
6232                return sus.pkgFlags;
6233            } else if (obj instanceof PackageSetting) {
6234                final PackageSetting ps = (PackageSetting) obj;
6235                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6236                    return 0;
6237                }
6238                return ps.pkgFlags;
6239            }
6240        }
6241        return 0;
6242    }
6243
6244    @Override
6245    public int getPrivateFlagsForUid(int uid) {
6246        final int callingUid = Binder.getCallingUid();
6247        if (getInstantAppPackageName(callingUid) != null) {
6248            return 0;
6249        }
6250        synchronized (mPackages) {
6251            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6252            if (obj instanceof SharedUserSetting) {
6253                final SharedUserSetting sus = (SharedUserSetting) obj;
6254                return sus.pkgPrivateFlags;
6255            } else if (obj instanceof PackageSetting) {
6256                final PackageSetting ps = (PackageSetting) obj;
6257                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6258                    return 0;
6259                }
6260                return ps.pkgPrivateFlags;
6261            }
6262        }
6263        return 0;
6264    }
6265
6266    @Override
6267    public boolean isUidPrivileged(int uid) {
6268        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6269            return false;
6270        }
6271        uid = UserHandle.getAppId(uid);
6272        // reader
6273        synchronized (mPackages) {
6274            Object obj = mSettings.getUserIdLPr(uid);
6275            if (obj instanceof SharedUserSetting) {
6276                final SharedUserSetting sus = (SharedUserSetting) obj;
6277                final Iterator<PackageSetting> it = sus.packages.iterator();
6278                while (it.hasNext()) {
6279                    if (it.next().isPrivileged()) {
6280                        return true;
6281                    }
6282                }
6283            } else if (obj instanceof PackageSetting) {
6284                final PackageSetting ps = (PackageSetting) obj;
6285                return ps.isPrivileged();
6286            }
6287        }
6288        return false;
6289    }
6290
6291    @Override
6292    public String[] getAppOpPermissionPackages(String permissionName) {
6293        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6294            return null;
6295        }
6296        synchronized (mPackages) {
6297            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6298            if (pkgs == null) {
6299                return null;
6300            }
6301            return pkgs.toArray(new String[pkgs.size()]);
6302        }
6303    }
6304
6305    @Override
6306    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6307            int flags, int userId) {
6308        return resolveIntentInternal(
6309                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6310    }
6311
6312    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6313            int flags, int userId, boolean resolveForStart) {
6314        try {
6315            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6316
6317            if (!sUserManager.exists(userId)) return null;
6318            final int callingUid = Binder.getCallingUid();
6319            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6320            enforceCrossUserPermission(callingUid, userId,
6321                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6322
6323            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6324            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6325                    flags, callingUid, userId, resolveForStart);
6326            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6327
6328            final ResolveInfo bestChoice =
6329                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6330            return bestChoice;
6331        } finally {
6332            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6333        }
6334    }
6335
6336    @Override
6337    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6338        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6339            throw new SecurityException(
6340                    "findPersistentPreferredActivity can only be run by the system");
6341        }
6342        if (!sUserManager.exists(userId)) {
6343            return null;
6344        }
6345        final int callingUid = Binder.getCallingUid();
6346        intent = updateIntentForResolve(intent);
6347        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6348        final int flags = updateFlagsForResolve(
6349                0, userId, intent, callingUid, false /*includeInstantApps*/);
6350        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6351                userId);
6352        synchronized (mPackages) {
6353            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6354                    userId);
6355        }
6356    }
6357
6358    @Override
6359    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6360            IntentFilter filter, int match, ComponentName activity) {
6361        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6362            return;
6363        }
6364        final int userId = UserHandle.getCallingUserId();
6365        if (DEBUG_PREFERRED) {
6366            Log.v(TAG, "setLastChosenActivity intent=" + intent
6367                + " resolvedType=" + resolvedType
6368                + " flags=" + flags
6369                + " filter=" + filter
6370                + " match=" + match
6371                + " activity=" + activity);
6372            filter.dump(new PrintStreamPrinter(System.out), "    ");
6373        }
6374        intent.setComponent(null);
6375        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6376                userId);
6377        // Find any earlier preferred or last chosen entries and nuke them
6378        findPreferredActivity(intent, resolvedType,
6379                flags, query, 0, false, true, false, userId);
6380        // Add the new activity as the last chosen for this filter
6381        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6382                "Setting last chosen");
6383    }
6384
6385    @Override
6386    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6387        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6388            return null;
6389        }
6390        final int userId = UserHandle.getCallingUserId();
6391        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6392        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6393                userId);
6394        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6395                false, false, false, userId);
6396    }
6397
6398    /**
6399     * Returns whether or not instant apps have been disabled remotely.
6400     */
6401    private boolean isEphemeralDisabled() {
6402        return mEphemeralAppsDisabled;
6403    }
6404
6405    private boolean isInstantAppAllowed(
6406            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6407            boolean skipPackageCheck) {
6408        if (mInstantAppResolverConnection == null) {
6409            return false;
6410        }
6411        if (mInstantAppInstallerActivity == null) {
6412            return false;
6413        }
6414        if (intent.getComponent() != null) {
6415            return false;
6416        }
6417        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6418            return false;
6419        }
6420        if (!skipPackageCheck && intent.getPackage() != null) {
6421            return false;
6422        }
6423        final boolean isWebUri = hasWebURI(intent);
6424        if (!isWebUri || intent.getData().getHost() == null) {
6425            return false;
6426        }
6427        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6428        // Or if there's already an ephemeral app installed that handles the action
6429        synchronized (mPackages) {
6430            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6431            for (int n = 0; n < count; n++) {
6432                final ResolveInfo info = resolvedActivities.get(n);
6433                final String packageName = info.activityInfo.packageName;
6434                final PackageSetting ps = mSettings.mPackages.get(packageName);
6435                if (ps != null) {
6436                    // only check domain verification status if the app is not a browser
6437                    if (!info.handleAllWebDataURI) {
6438                        // Try to get the status from User settings first
6439                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6440                        final int status = (int) (packedStatus >> 32);
6441                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6442                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6443                            if (DEBUG_EPHEMERAL) {
6444                                Slog.v(TAG, "DENY instant app;"
6445                                    + " pkg: " + packageName + ", status: " + status);
6446                            }
6447                            return false;
6448                        }
6449                    }
6450                    if (ps.getInstantApp(userId)) {
6451                        if (DEBUG_EPHEMERAL) {
6452                            Slog.v(TAG, "DENY instant app installed;"
6453                                    + " pkg: " + packageName);
6454                        }
6455                        return false;
6456                    }
6457                }
6458            }
6459        }
6460        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6461        return true;
6462    }
6463
6464    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6465            Intent origIntent, String resolvedType, String callingPackage,
6466            Bundle verificationBundle, int userId) {
6467        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6468                new InstantAppRequest(responseObj, origIntent, resolvedType,
6469                        callingPackage, userId, verificationBundle));
6470        mHandler.sendMessage(msg);
6471    }
6472
6473    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6474            int flags, List<ResolveInfo> query, int userId) {
6475        if (query != null) {
6476            final int N = query.size();
6477            if (N == 1) {
6478                return query.get(0);
6479            } else if (N > 1) {
6480                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6481                // If there is more than one activity with the same priority,
6482                // then let the user decide between them.
6483                ResolveInfo r0 = query.get(0);
6484                ResolveInfo r1 = query.get(1);
6485                if (DEBUG_INTENT_MATCHING || debug) {
6486                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6487                            + r1.activityInfo.name + "=" + r1.priority);
6488                }
6489                // If the first activity has a higher priority, or a different
6490                // default, then it is always desirable to pick it.
6491                if (r0.priority != r1.priority
6492                        || r0.preferredOrder != r1.preferredOrder
6493                        || r0.isDefault != r1.isDefault) {
6494                    return query.get(0);
6495                }
6496                // If we have saved a preference for a preferred activity for
6497                // this Intent, use that.
6498                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6499                        flags, query, r0.priority, true, false, debug, userId);
6500                if (ri != null) {
6501                    return ri;
6502                }
6503                // If we have an ephemeral app, use it
6504                for (int i = 0; i < N; i++) {
6505                    ri = query.get(i);
6506                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6507                        final String packageName = ri.activityInfo.packageName;
6508                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6509                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6510                        final int status = (int)(packedStatus >> 32);
6511                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6512                            return ri;
6513                        }
6514                    }
6515                }
6516                ri = new ResolveInfo(mResolveInfo);
6517                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6518                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6519                // If all of the options come from the same package, show the application's
6520                // label and icon instead of the generic resolver's.
6521                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6522                // and then throw away the ResolveInfo itself, meaning that the caller loses
6523                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6524                // a fallback for this case; we only set the target package's resources on
6525                // the ResolveInfo, not the ActivityInfo.
6526                final String intentPackage = intent.getPackage();
6527                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6528                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6529                    ri.resolvePackageName = intentPackage;
6530                    if (userNeedsBadging(userId)) {
6531                        ri.noResourceId = true;
6532                    } else {
6533                        ri.icon = appi.icon;
6534                    }
6535                    ri.iconResourceId = appi.icon;
6536                    ri.labelRes = appi.labelRes;
6537                }
6538                ri.activityInfo.applicationInfo = new ApplicationInfo(
6539                        ri.activityInfo.applicationInfo);
6540                if (userId != 0) {
6541                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6542                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6543                }
6544                // Make sure that the resolver is displayable in car mode
6545                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6546                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6547                return ri;
6548            }
6549        }
6550        return null;
6551    }
6552
6553    /**
6554     * Return true if the given list is not empty and all of its contents have
6555     * an activityInfo with the given package name.
6556     */
6557    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6558        if (ArrayUtils.isEmpty(list)) {
6559            return false;
6560        }
6561        for (int i = 0, N = list.size(); i < N; i++) {
6562            final ResolveInfo ri = list.get(i);
6563            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6564            if (ai == null || !packageName.equals(ai.packageName)) {
6565                return false;
6566            }
6567        }
6568        return true;
6569    }
6570
6571    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6572            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6573        final int N = query.size();
6574        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6575                .get(userId);
6576        // Get the list of persistent preferred activities that handle the intent
6577        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6578        List<PersistentPreferredActivity> pprefs = ppir != null
6579                ? ppir.queryIntent(intent, resolvedType,
6580                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6581                        userId)
6582                : null;
6583        if (pprefs != null && pprefs.size() > 0) {
6584            final int M = pprefs.size();
6585            for (int i=0; i<M; i++) {
6586                final PersistentPreferredActivity ppa = pprefs.get(i);
6587                if (DEBUG_PREFERRED || debug) {
6588                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6589                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6590                            + "\n  component=" + ppa.mComponent);
6591                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6592                }
6593                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6594                        flags | MATCH_DISABLED_COMPONENTS, userId);
6595                if (DEBUG_PREFERRED || debug) {
6596                    Slog.v(TAG, "Found persistent preferred activity:");
6597                    if (ai != null) {
6598                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6599                    } else {
6600                        Slog.v(TAG, "  null");
6601                    }
6602                }
6603                if (ai == null) {
6604                    // This previously registered persistent preferred activity
6605                    // component is no longer known. Ignore it and do NOT remove it.
6606                    continue;
6607                }
6608                for (int j=0; j<N; j++) {
6609                    final ResolveInfo ri = query.get(j);
6610                    if (!ri.activityInfo.applicationInfo.packageName
6611                            .equals(ai.applicationInfo.packageName)) {
6612                        continue;
6613                    }
6614                    if (!ri.activityInfo.name.equals(ai.name)) {
6615                        continue;
6616                    }
6617                    //  Found a persistent preference that can handle the intent.
6618                    if (DEBUG_PREFERRED || debug) {
6619                        Slog.v(TAG, "Returning persistent preferred activity: " +
6620                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6621                    }
6622                    return ri;
6623                }
6624            }
6625        }
6626        return null;
6627    }
6628
6629    // TODO: handle preferred activities missing while user has amnesia
6630    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6631            List<ResolveInfo> query, int priority, boolean always,
6632            boolean removeMatches, boolean debug, int userId) {
6633        if (!sUserManager.exists(userId)) return null;
6634        final int callingUid = Binder.getCallingUid();
6635        flags = updateFlagsForResolve(
6636                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6637        intent = updateIntentForResolve(intent);
6638        // writer
6639        synchronized (mPackages) {
6640            // Try to find a matching persistent preferred activity.
6641            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6642                    debug, userId);
6643
6644            // If a persistent preferred activity matched, use it.
6645            if (pri != null) {
6646                return pri;
6647            }
6648
6649            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6650            // Get the list of preferred activities that handle the intent
6651            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6652            List<PreferredActivity> prefs = pir != null
6653                    ? pir.queryIntent(intent, resolvedType,
6654                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6655                            userId)
6656                    : null;
6657            if (prefs != null && prefs.size() > 0) {
6658                boolean changed = false;
6659                try {
6660                    // First figure out how good the original match set is.
6661                    // We will only allow preferred activities that came
6662                    // from the same match quality.
6663                    int match = 0;
6664
6665                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6666
6667                    final int N = query.size();
6668                    for (int j=0; j<N; j++) {
6669                        final ResolveInfo ri = query.get(j);
6670                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6671                                + ": 0x" + Integer.toHexString(match));
6672                        if (ri.match > match) {
6673                            match = ri.match;
6674                        }
6675                    }
6676
6677                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6678                            + Integer.toHexString(match));
6679
6680                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6681                    final int M = prefs.size();
6682                    for (int i=0; i<M; i++) {
6683                        final PreferredActivity pa = prefs.get(i);
6684                        if (DEBUG_PREFERRED || debug) {
6685                            Slog.v(TAG, "Checking PreferredActivity ds="
6686                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6687                                    + "\n  component=" + pa.mPref.mComponent);
6688                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6689                        }
6690                        if (pa.mPref.mMatch != match) {
6691                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6692                                    + Integer.toHexString(pa.mPref.mMatch));
6693                            continue;
6694                        }
6695                        // If it's not an "always" type preferred activity and that's what we're
6696                        // looking for, skip it.
6697                        if (always && !pa.mPref.mAlways) {
6698                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6699                            continue;
6700                        }
6701                        final ActivityInfo ai = getActivityInfo(
6702                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6703                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6704                                userId);
6705                        if (DEBUG_PREFERRED || debug) {
6706                            Slog.v(TAG, "Found preferred activity:");
6707                            if (ai != null) {
6708                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6709                            } else {
6710                                Slog.v(TAG, "  null");
6711                            }
6712                        }
6713                        if (ai == null) {
6714                            // This previously registered preferred activity
6715                            // component is no longer known.  Most likely an update
6716                            // to the app was installed and in the new version this
6717                            // component no longer exists.  Clean it up by removing
6718                            // it from the preferred activities list, and skip it.
6719                            Slog.w(TAG, "Removing dangling preferred activity: "
6720                                    + pa.mPref.mComponent);
6721                            pir.removeFilter(pa);
6722                            changed = true;
6723                            continue;
6724                        }
6725                        for (int j=0; j<N; j++) {
6726                            final ResolveInfo ri = query.get(j);
6727                            if (!ri.activityInfo.applicationInfo.packageName
6728                                    .equals(ai.applicationInfo.packageName)) {
6729                                continue;
6730                            }
6731                            if (!ri.activityInfo.name.equals(ai.name)) {
6732                                continue;
6733                            }
6734
6735                            if (removeMatches) {
6736                                pir.removeFilter(pa);
6737                                changed = true;
6738                                if (DEBUG_PREFERRED) {
6739                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6740                                }
6741                                break;
6742                            }
6743
6744                            // Okay we found a previously set preferred or last chosen app.
6745                            // If the result set is different from when this
6746                            // was created, we need to clear it and re-ask the
6747                            // user their preference, if we're looking for an "always" type entry.
6748                            if (always && !pa.mPref.sameSet(query)) {
6749                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6750                                        + intent + " type " + resolvedType);
6751                                if (DEBUG_PREFERRED) {
6752                                    Slog.v(TAG, "Removing preferred activity since set changed "
6753                                            + pa.mPref.mComponent);
6754                                }
6755                                pir.removeFilter(pa);
6756                                // Re-add the filter as a "last chosen" entry (!always)
6757                                PreferredActivity lastChosen = new PreferredActivity(
6758                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6759                                pir.addFilter(lastChosen);
6760                                changed = true;
6761                                return null;
6762                            }
6763
6764                            // Yay! Either the set matched or we're looking for the last chosen
6765                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6766                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6767                            return ri;
6768                        }
6769                    }
6770                } finally {
6771                    if (changed) {
6772                        if (DEBUG_PREFERRED) {
6773                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6774                        }
6775                        scheduleWritePackageRestrictionsLocked(userId);
6776                    }
6777                }
6778            }
6779        }
6780        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6781        return null;
6782    }
6783
6784    /*
6785     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6786     */
6787    @Override
6788    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6789            int targetUserId) {
6790        mContext.enforceCallingOrSelfPermission(
6791                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6792        List<CrossProfileIntentFilter> matches =
6793                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6794        if (matches != null) {
6795            int size = matches.size();
6796            for (int i = 0; i < size; i++) {
6797                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6798            }
6799        }
6800        if (hasWebURI(intent)) {
6801            // cross-profile app linking works only towards the parent.
6802            final int callingUid = Binder.getCallingUid();
6803            final UserInfo parent = getProfileParent(sourceUserId);
6804            synchronized(mPackages) {
6805                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6806                        false /*includeInstantApps*/);
6807                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6808                        intent, resolvedType, flags, sourceUserId, parent.id);
6809                return xpDomainInfo != null;
6810            }
6811        }
6812        return false;
6813    }
6814
6815    private UserInfo getProfileParent(int userId) {
6816        final long identity = Binder.clearCallingIdentity();
6817        try {
6818            return sUserManager.getProfileParent(userId);
6819        } finally {
6820            Binder.restoreCallingIdentity(identity);
6821        }
6822    }
6823
6824    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6825            String resolvedType, int userId) {
6826        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6827        if (resolver != null) {
6828            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6829        }
6830        return null;
6831    }
6832
6833    @Override
6834    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6835            String resolvedType, int flags, int userId) {
6836        try {
6837            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6838
6839            return new ParceledListSlice<>(
6840                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6841        } finally {
6842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6843        }
6844    }
6845
6846    /**
6847     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6848     * instant, returns {@code null}.
6849     */
6850    private String getInstantAppPackageName(int callingUid) {
6851        synchronized (mPackages) {
6852            // If the caller is an isolated app use the owner's uid for the lookup.
6853            if (Process.isIsolated(callingUid)) {
6854                callingUid = mIsolatedOwners.get(callingUid);
6855            }
6856            final int appId = UserHandle.getAppId(callingUid);
6857            final Object obj = mSettings.getUserIdLPr(appId);
6858            if (obj instanceof PackageSetting) {
6859                final PackageSetting ps = (PackageSetting) obj;
6860                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6861                return isInstantApp ? ps.pkg.packageName : null;
6862            }
6863        }
6864        return null;
6865    }
6866
6867    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6868            String resolvedType, int flags, int userId) {
6869        return queryIntentActivitiesInternal(
6870                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6871    }
6872
6873    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6874            String resolvedType, int flags, int filterCallingUid, int userId,
6875            boolean resolveForStart) {
6876        if (!sUserManager.exists(userId)) return Collections.emptyList();
6877        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6878        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6879                false /* requireFullPermission */, false /* checkShell */,
6880                "query intent activities");
6881        final String pkgName = intent.getPackage();
6882        ComponentName comp = intent.getComponent();
6883        if (comp == null) {
6884            if (intent.getSelector() != null) {
6885                intent = intent.getSelector();
6886                comp = intent.getComponent();
6887            }
6888        }
6889
6890        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6891                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6892        if (comp != null) {
6893            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6894            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6895            if (ai != null) {
6896                // When specifying an explicit component, we prevent the activity from being
6897                // used when either 1) the calling package is normal and the activity is within
6898                // an ephemeral application or 2) the calling package is ephemeral and the
6899                // activity is not visible to ephemeral applications.
6900                final boolean matchInstantApp =
6901                        (flags & PackageManager.MATCH_INSTANT) != 0;
6902                final boolean matchVisibleToInstantAppOnly =
6903                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6904                final boolean matchExplicitlyVisibleOnly =
6905                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6906                final boolean isCallerInstantApp =
6907                        instantAppPkgName != null;
6908                final boolean isTargetSameInstantApp =
6909                        comp.getPackageName().equals(instantAppPkgName);
6910                final boolean isTargetInstantApp =
6911                        (ai.applicationInfo.privateFlags
6912                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6913                final boolean isTargetVisibleToInstantApp =
6914                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6915                final boolean isTargetExplicitlyVisibleToInstantApp =
6916                        isTargetVisibleToInstantApp
6917                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6918                final boolean isTargetHiddenFromInstantApp =
6919                        !isTargetVisibleToInstantApp
6920                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6921                final boolean blockResolution =
6922                        !isTargetSameInstantApp
6923                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6924                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6925                                        && isTargetHiddenFromInstantApp));
6926                if (!blockResolution) {
6927                    final ResolveInfo ri = new ResolveInfo();
6928                    ri.activityInfo = ai;
6929                    list.add(ri);
6930                }
6931            }
6932            return applyPostResolutionFilter(list, instantAppPkgName);
6933        }
6934
6935        // reader
6936        boolean sortResult = false;
6937        boolean addEphemeral = false;
6938        List<ResolveInfo> result;
6939        final boolean ephemeralDisabled = isEphemeralDisabled();
6940        synchronized (mPackages) {
6941            if (pkgName == null) {
6942                List<CrossProfileIntentFilter> matchingFilters =
6943                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6944                // Check for results that need to skip the current profile.
6945                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6946                        resolvedType, flags, userId);
6947                if (xpResolveInfo != null) {
6948                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6949                    xpResult.add(xpResolveInfo);
6950                    return applyPostResolutionFilter(
6951                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6952                }
6953
6954                // Check for results in the current profile.
6955                result = filterIfNotSystemUser(mActivities.queryIntent(
6956                        intent, resolvedType, flags, userId), userId);
6957                addEphemeral = !ephemeralDisabled
6958                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6959                // Check for cross profile results.
6960                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6961                xpResolveInfo = queryCrossProfileIntents(
6962                        matchingFilters, intent, resolvedType, flags, userId,
6963                        hasNonNegativePriorityResult);
6964                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6965                    boolean isVisibleToUser = filterIfNotSystemUser(
6966                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6967                    if (isVisibleToUser) {
6968                        result.add(xpResolveInfo);
6969                        sortResult = true;
6970                    }
6971                }
6972                if (hasWebURI(intent)) {
6973                    CrossProfileDomainInfo xpDomainInfo = null;
6974                    final UserInfo parent = getProfileParent(userId);
6975                    if (parent != null) {
6976                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6977                                flags, userId, parent.id);
6978                    }
6979                    if (xpDomainInfo != null) {
6980                        if (xpResolveInfo != null) {
6981                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6982                            // in the result.
6983                            result.remove(xpResolveInfo);
6984                        }
6985                        if (result.size() == 0 && !addEphemeral) {
6986                            // No result in current profile, but found candidate in parent user.
6987                            // And we are not going to add emphemeral app, so we can return the
6988                            // result straight away.
6989                            result.add(xpDomainInfo.resolveInfo);
6990                            return applyPostResolutionFilter(result, instantAppPkgName);
6991                        }
6992                    } else if (result.size() <= 1 && !addEphemeral) {
6993                        // No result in parent user and <= 1 result in current profile, and we
6994                        // are not going to add emphemeral app, so we can return the result without
6995                        // further processing.
6996                        return applyPostResolutionFilter(result, instantAppPkgName);
6997                    }
6998                    // We have more than one candidate (combining results from current and parent
6999                    // profile), so we need filtering and sorting.
7000                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7001                            intent, flags, result, xpDomainInfo, userId);
7002                    sortResult = true;
7003                }
7004            } else {
7005                final PackageParser.Package pkg = mPackages.get(pkgName);
7006                result = null;
7007                if (pkg != null) {
7008                    result = filterIfNotSystemUser(
7009                            mActivities.queryIntentForPackage(
7010                                    intent, resolvedType, flags, pkg.activities, userId),
7011                            userId);
7012                }
7013                if (result == null || result.size() == 0) {
7014                    // the caller wants to resolve for a particular package; however, there
7015                    // were no installed results, so, try to find an ephemeral result
7016                    addEphemeral = !ephemeralDisabled
7017                            && isInstantAppAllowed(
7018                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7019                    if (result == null) {
7020                        result = new ArrayList<>();
7021                    }
7022                }
7023            }
7024        }
7025        if (addEphemeral) {
7026            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7027        }
7028        if (sortResult) {
7029            Collections.sort(result, mResolvePrioritySorter);
7030        }
7031        return applyPostResolutionFilter(result, instantAppPkgName);
7032    }
7033
7034    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7035            String resolvedType, int flags, int userId) {
7036        // first, check to see if we've got an instant app already installed
7037        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7038        ResolveInfo localInstantApp = null;
7039        boolean blockResolution = false;
7040        if (!alreadyResolvedLocally) {
7041            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7042                    flags
7043                        | PackageManager.GET_RESOLVED_FILTER
7044                        | PackageManager.MATCH_INSTANT
7045                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7046                    userId);
7047            for (int i = instantApps.size() - 1; i >= 0; --i) {
7048                final ResolveInfo info = instantApps.get(i);
7049                final String packageName = info.activityInfo.packageName;
7050                final PackageSetting ps = mSettings.mPackages.get(packageName);
7051                if (ps.getInstantApp(userId)) {
7052                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7053                    final int status = (int)(packedStatus >> 32);
7054                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7055                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7056                        // there's a local instant application installed, but, the user has
7057                        // chosen to never use it; skip resolution and don't acknowledge
7058                        // an instant application is even available
7059                        if (DEBUG_EPHEMERAL) {
7060                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7061                        }
7062                        blockResolution = true;
7063                        break;
7064                    } else {
7065                        // we have a locally installed instant application; skip resolution
7066                        // but acknowledge there's an instant application available
7067                        if (DEBUG_EPHEMERAL) {
7068                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7069                        }
7070                        localInstantApp = info;
7071                        break;
7072                    }
7073                }
7074            }
7075        }
7076        // no app installed, let's see if one's available
7077        AuxiliaryResolveInfo auxiliaryResponse = null;
7078        if (!blockResolution) {
7079            if (localInstantApp == null) {
7080                // we don't have an instant app locally, resolve externally
7081                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7082                final InstantAppRequest requestObject = new InstantAppRequest(
7083                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7084                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7085                auxiliaryResponse =
7086                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7087                                mContext, mInstantAppResolverConnection, requestObject);
7088                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7089            } else {
7090                // we have an instant application locally, but, we can't admit that since
7091                // callers shouldn't be able to determine prior browsing. create a dummy
7092                // auxiliary response so the downstream code behaves as if there's an
7093                // instant application available externally. when it comes time to start
7094                // the instant application, we'll do the right thing.
7095                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7096                auxiliaryResponse = new AuxiliaryResolveInfo(
7097                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7098            }
7099        }
7100        if (auxiliaryResponse != null) {
7101            if (DEBUG_EPHEMERAL) {
7102                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7103            }
7104            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7105            final PackageSetting ps =
7106                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7107            if (ps != null) {
7108                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7109                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7110                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7111                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7112                // make sure this resolver is the default
7113                ephemeralInstaller.isDefault = true;
7114                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7115                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7116                // add a non-generic filter
7117                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7118                ephemeralInstaller.filter.addDataPath(
7119                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7120                ephemeralInstaller.isInstantAppAvailable = true;
7121                result.add(ephemeralInstaller);
7122            }
7123        }
7124        return result;
7125    }
7126
7127    private static class CrossProfileDomainInfo {
7128        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7129        ResolveInfo resolveInfo;
7130        /* Best domain verification status of the activities found in the other profile */
7131        int bestDomainVerificationStatus;
7132    }
7133
7134    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7135            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7136        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7137                sourceUserId)) {
7138            return null;
7139        }
7140        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7141                resolvedType, flags, parentUserId);
7142
7143        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7144            return null;
7145        }
7146        CrossProfileDomainInfo result = null;
7147        int size = resultTargetUser.size();
7148        for (int i = 0; i < size; i++) {
7149            ResolveInfo riTargetUser = resultTargetUser.get(i);
7150            // Intent filter verification is only for filters that specify a host. So don't return
7151            // those that handle all web uris.
7152            if (riTargetUser.handleAllWebDataURI) {
7153                continue;
7154            }
7155            String packageName = riTargetUser.activityInfo.packageName;
7156            PackageSetting ps = mSettings.mPackages.get(packageName);
7157            if (ps == null) {
7158                continue;
7159            }
7160            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7161            int status = (int)(verificationState >> 32);
7162            if (result == null) {
7163                result = new CrossProfileDomainInfo();
7164                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7165                        sourceUserId, parentUserId);
7166                result.bestDomainVerificationStatus = status;
7167            } else {
7168                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7169                        result.bestDomainVerificationStatus);
7170            }
7171        }
7172        // Don't consider matches with status NEVER across profiles.
7173        if (result != null && result.bestDomainVerificationStatus
7174                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7175            return null;
7176        }
7177        return result;
7178    }
7179
7180    /**
7181     * Verification statuses are ordered from the worse to the best, except for
7182     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7183     */
7184    private int bestDomainVerificationStatus(int status1, int status2) {
7185        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7186            return status2;
7187        }
7188        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7189            return status1;
7190        }
7191        return (int) MathUtils.max(status1, status2);
7192    }
7193
7194    private boolean isUserEnabled(int userId) {
7195        long callingId = Binder.clearCallingIdentity();
7196        try {
7197            UserInfo userInfo = sUserManager.getUserInfo(userId);
7198            return userInfo != null && userInfo.isEnabled();
7199        } finally {
7200            Binder.restoreCallingIdentity(callingId);
7201        }
7202    }
7203
7204    /**
7205     * Filter out activities with systemUserOnly flag set, when current user is not System.
7206     *
7207     * @return filtered list
7208     */
7209    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7210        if (userId == UserHandle.USER_SYSTEM) {
7211            return resolveInfos;
7212        }
7213        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7214            ResolveInfo info = resolveInfos.get(i);
7215            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7216                resolveInfos.remove(i);
7217            }
7218        }
7219        return resolveInfos;
7220    }
7221
7222    /**
7223     * Filters out ephemeral activities.
7224     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7225     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7226     *
7227     * @param resolveInfos The pre-filtered list of resolved activities
7228     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7229     *          is performed.
7230     * @return A filtered list of resolved activities.
7231     */
7232    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7233            String ephemeralPkgName) {
7234        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7235            final ResolveInfo info = resolveInfos.get(i);
7236            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7237            // TODO: When adding on-demand split support for non-instant apps, remove this check
7238            // and always apply post filtering
7239            // allow activities that are defined in the provided package
7240            if (isEphemeralApp) {
7241                if (info.activityInfo.splitName != null
7242                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7243                                info.activityInfo.splitName)) {
7244                    // requested activity is defined in a split that hasn't been installed yet.
7245                    // add the installer to the resolve list
7246                    if (DEBUG_EPHEMERAL) {
7247                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7248                    }
7249                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7250                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7251                            info.activityInfo.packageName, info.activityInfo.splitName,
7252                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7253                    // make sure this resolver is the default
7254                    installerInfo.isDefault = true;
7255                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7256                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7257                    // add a non-generic filter
7258                    installerInfo.filter = new IntentFilter();
7259                    // load resources from the correct package
7260                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7261                    resolveInfos.set(i, installerInfo);
7262                    continue;
7263                }
7264            }
7265            // caller is a full app, don't need to apply any other filtering
7266            if (ephemeralPkgName == null) {
7267                continue;
7268            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7269                // caller is same app; don't need to apply any other filtering
7270                continue;
7271            }
7272            // allow activities that have been explicitly exposed to ephemeral apps
7273            if (!isEphemeralApp
7274                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7275                continue;
7276            }
7277            resolveInfos.remove(i);
7278        }
7279        return resolveInfos;
7280    }
7281
7282    /**
7283     * @param resolveInfos list of resolve infos in descending priority order
7284     * @return if the list contains a resolve info with non-negative priority
7285     */
7286    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7287        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7288    }
7289
7290    private static boolean hasWebURI(Intent intent) {
7291        if (intent.getData() == null) {
7292            return false;
7293        }
7294        final String scheme = intent.getScheme();
7295        if (TextUtils.isEmpty(scheme)) {
7296            return false;
7297        }
7298        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7299    }
7300
7301    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7302            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7303            int userId) {
7304        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7305
7306        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7307            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7308                    candidates.size());
7309        }
7310
7311        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7312        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7313        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7314        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7315        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7316        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7317
7318        synchronized (mPackages) {
7319            final int count = candidates.size();
7320            // First, try to use linked apps. Partition the candidates into four lists:
7321            // one for the final results, one for the "do not use ever", one for "undefined status"
7322            // and finally one for "browser app type".
7323            for (int n=0; n<count; n++) {
7324                ResolveInfo info = candidates.get(n);
7325                String packageName = info.activityInfo.packageName;
7326                PackageSetting ps = mSettings.mPackages.get(packageName);
7327                if (ps != null) {
7328                    // Add to the special match all list (Browser use case)
7329                    if (info.handleAllWebDataURI) {
7330                        matchAllList.add(info);
7331                        continue;
7332                    }
7333                    // Try to get the status from User settings first
7334                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7335                    int status = (int)(packedStatus >> 32);
7336                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7337                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7338                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7339                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7340                                    + " : linkgen=" + linkGeneration);
7341                        }
7342                        // Use link-enabled generation as preferredOrder, i.e.
7343                        // prefer newly-enabled over earlier-enabled.
7344                        info.preferredOrder = linkGeneration;
7345                        alwaysList.add(info);
7346                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7347                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7348                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7349                        }
7350                        neverList.add(info);
7351                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7352                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7353                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7354                        }
7355                        alwaysAskList.add(info);
7356                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7357                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7358                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7359                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7360                        }
7361                        undefinedList.add(info);
7362                    }
7363                }
7364            }
7365
7366            // We'll want to include browser possibilities in a few cases
7367            boolean includeBrowser = false;
7368
7369            // First try to add the "always" resolution(s) for the current user, if any
7370            if (alwaysList.size() > 0) {
7371                result.addAll(alwaysList);
7372            } else {
7373                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7374                result.addAll(undefinedList);
7375                // Maybe add one for the other profile.
7376                if (xpDomainInfo != null && (
7377                        xpDomainInfo.bestDomainVerificationStatus
7378                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7379                    result.add(xpDomainInfo.resolveInfo);
7380                }
7381                includeBrowser = true;
7382            }
7383
7384            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7385            // If there were 'always' entries their preferred order has been set, so we also
7386            // back that off to make the alternatives equivalent
7387            if (alwaysAskList.size() > 0) {
7388                for (ResolveInfo i : result) {
7389                    i.preferredOrder = 0;
7390                }
7391                result.addAll(alwaysAskList);
7392                includeBrowser = true;
7393            }
7394
7395            if (includeBrowser) {
7396                // Also add browsers (all of them or only the default one)
7397                if (DEBUG_DOMAIN_VERIFICATION) {
7398                    Slog.v(TAG, "   ...including browsers in candidate set");
7399                }
7400                if ((matchFlags & MATCH_ALL) != 0) {
7401                    result.addAll(matchAllList);
7402                } else {
7403                    // Browser/generic handling case.  If there's a default browser, go straight
7404                    // to that (but only if there is no other higher-priority match).
7405                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7406                    int maxMatchPrio = 0;
7407                    ResolveInfo defaultBrowserMatch = null;
7408                    final int numCandidates = matchAllList.size();
7409                    for (int n = 0; n < numCandidates; n++) {
7410                        ResolveInfo info = matchAllList.get(n);
7411                        // track the highest overall match priority...
7412                        if (info.priority > maxMatchPrio) {
7413                            maxMatchPrio = info.priority;
7414                        }
7415                        // ...and the highest-priority default browser match
7416                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7417                            if (defaultBrowserMatch == null
7418                                    || (defaultBrowserMatch.priority < info.priority)) {
7419                                if (debug) {
7420                                    Slog.v(TAG, "Considering default browser match " + info);
7421                                }
7422                                defaultBrowserMatch = info;
7423                            }
7424                        }
7425                    }
7426                    if (defaultBrowserMatch != null
7427                            && defaultBrowserMatch.priority >= maxMatchPrio
7428                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7429                    {
7430                        if (debug) {
7431                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7432                        }
7433                        result.add(defaultBrowserMatch);
7434                    } else {
7435                        result.addAll(matchAllList);
7436                    }
7437                }
7438
7439                // If there is nothing selected, add all candidates and remove the ones that the user
7440                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7441                if (result.size() == 0) {
7442                    result.addAll(candidates);
7443                    result.removeAll(neverList);
7444                }
7445            }
7446        }
7447        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7448            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7449                    result.size());
7450            for (ResolveInfo info : result) {
7451                Slog.v(TAG, "  + " + info.activityInfo);
7452            }
7453        }
7454        return result;
7455    }
7456
7457    // Returns a packed value as a long:
7458    //
7459    // high 'int'-sized word: link status: undefined/ask/never/always.
7460    // low 'int'-sized word: relative priority among 'always' results.
7461    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7462        long result = ps.getDomainVerificationStatusForUser(userId);
7463        // if none available, get the master status
7464        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7465            if (ps.getIntentFilterVerificationInfo() != null) {
7466                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7467            }
7468        }
7469        return result;
7470    }
7471
7472    private ResolveInfo querySkipCurrentProfileIntents(
7473            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7474            int flags, int sourceUserId) {
7475        if (matchingFilters != null) {
7476            int size = matchingFilters.size();
7477            for (int i = 0; i < size; i ++) {
7478                CrossProfileIntentFilter filter = matchingFilters.get(i);
7479                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7480                    // Checking if there are activities in the target user that can handle the
7481                    // intent.
7482                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7483                            resolvedType, flags, sourceUserId);
7484                    if (resolveInfo != null) {
7485                        return resolveInfo;
7486                    }
7487                }
7488            }
7489        }
7490        return null;
7491    }
7492
7493    // Return matching ResolveInfo in target user if any.
7494    private ResolveInfo queryCrossProfileIntents(
7495            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7496            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7497        if (matchingFilters != null) {
7498            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7499            // match the same intent. For performance reasons, it is better not to
7500            // run queryIntent twice for the same userId
7501            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7502            int size = matchingFilters.size();
7503            for (int i = 0; i < size; i++) {
7504                CrossProfileIntentFilter filter = matchingFilters.get(i);
7505                int targetUserId = filter.getTargetUserId();
7506                boolean skipCurrentProfile =
7507                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7508                boolean skipCurrentProfileIfNoMatchFound =
7509                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7510                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7511                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7512                    // Checking if there are activities in the target user that can handle the
7513                    // intent.
7514                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7515                            resolvedType, flags, sourceUserId);
7516                    if (resolveInfo != null) return resolveInfo;
7517                    alreadyTriedUserIds.put(targetUserId, true);
7518                }
7519            }
7520        }
7521        return null;
7522    }
7523
7524    /**
7525     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7526     * will forward the intent to the filter's target user.
7527     * Otherwise, returns null.
7528     */
7529    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7530            String resolvedType, int flags, int sourceUserId) {
7531        int targetUserId = filter.getTargetUserId();
7532        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7533                resolvedType, flags, targetUserId);
7534        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7535            // If all the matches in the target profile are suspended, return null.
7536            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7537                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7538                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7539                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7540                            targetUserId);
7541                }
7542            }
7543        }
7544        return null;
7545    }
7546
7547    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7548            int sourceUserId, int targetUserId) {
7549        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7550        long ident = Binder.clearCallingIdentity();
7551        boolean targetIsProfile;
7552        try {
7553            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7554        } finally {
7555            Binder.restoreCallingIdentity(ident);
7556        }
7557        String className;
7558        if (targetIsProfile) {
7559            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7560        } else {
7561            className = FORWARD_INTENT_TO_PARENT;
7562        }
7563        ComponentName forwardingActivityComponentName = new ComponentName(
7564                mAndroidApplication.packageName, className);
7565        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7566                sourceUserId);
7567        if (!targetIsProfile) {
7568            forwardingActivityInfo.showUserIcon = targetUserId;
7569            forwardingResolveInfo.noResourceId = true;
7570        }
7571        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7572        forwardingResolveInfo.priority = 0;
7573        forwardingResolveInfo.preferredOrder = 0;
7574        forwardingResolveInfo.match = 0;
7575        forwardingResolveInfo.isDefault = true;
7576        forwardingResolveInfo.filter = filter;
7577        forwardingResolveInfo.targetUserId = targetUserId;
7578        return forwardingResolveInfo;
7579    }
7580
7581    @Override
7582    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7583            Intent[] specifics, String[] specificTypes, Intent intent,
7584            String resolvedType, int flags, int userId) {
7585        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7586                specificTypes, intent, resolvedType, flags, userId));
7587    }
7588
7589    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7590            Intent[] specifics, String[] specificTypes, Intent intent,
7591            String resolvedType, int flags, int userId) {
7592        if (!sUserManager.exists(userId)) return Collections.emptyList();
7593        final int callingUid = Binder.getCallingUid();
7594        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7595                false /*includeInstantApps*/);
7596        enforceCrossUserPermission(callingUid, userId,
7597                false /*requireFullPermission*/, false /*checkShell*/,
7598                "query intent activity options");
7599        final String resultsAction = intent.getAction();
7600
7601        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7602                | PackageManager.GET_RESOLVED_FILTER, userId);
7603
7604        if (DEBUG_INTENT_MATCHING) {
7605            Log.v(TAG, "Query " + intent + ": " + results);
7606        }
7607
7608        int specificsPos = 0;
7609        int N;
7610
7611        // todo: note that the algorithm used here is O(N^2).  This
7612        // isn't a problem in our current environment, but if we start running
7613        // into situations where we have more than 5 or 10 matches then this
7614        // should probably be changed to something smarter...
7615
7616        // First we go through and resolve each of the specific items
7617        // that were supplied, taking care of removing any corresponding
7618        // duplicate items in the generic resolve list.
7619        if (specifics != null) {
7620            for (int i=0; i<specifics.length; i++) {
7621                final Intent sintent = specifics[i];
7622                if (sintent == null) {
7623                    continue;
7624                }
7625
7626                if (DEBUG_INTENT_MATCHING) {
7627                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7628                }
7629
7630                String action = sintent.getAction();
7631                if (resultsAction != null && resultsAction.equals(action)) {
7632                    // If this action was explicitly requested, then don't
7633                    // remove things that have it.
7634                    action = null;
7635                }
7636
7637                ResolveInfo ri = null;
7638                ActivityInfo ai = null;
7639
7640                ComponentName comp = sintent.getComponent();
7641                if (comp == null) {
7642                    ri = resolveIntent(
7643                        sintent,
7644                        specificTypes != null ? specificTypes[i] : null,
7645                            flags, userId);
7646                    if (ri == null) {
7647                        continue;
7648                    }
7649                    if (ri == mResolveInfo) {
7650                        // ACK!  Must do something better with this.
7651                    }
7652                    ai = ri.activityInfo;
7653                    comp = new ComponentName(ai.applicationInfo.packageName,
7654                            ai.name);
7655                } else {
7656                    ai = getActivityInfo(comp, flags, userId);
7657                    if (ai == null) {
7658                        continue;
7659                    }
7660                }
7661
7662                // Look for any generic query activities that are duplicates
7663                // of this specific one, and remove them from the results.
7664                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7665                N = results.size();
7666                int j;
7667                for (j=specificsPos; j<N; j++) {
7668                    ResolveInfo sri = results.get(j);
7669                    if ((sri.activityInfo.name.equals(comp.getClassName())
7670                            && sri.activityInfo.applicationInfo.packageName.equals(
7671                                    comp.getPackageName()))
7672                        || (action != null && sri.filter.matchAction(action))) {
7673                        results.remove(j);
7674                        if (DEBUG_INTENT_MATCHING) Log.v(
7675                            TAG, "Removing duplicate item from " + j
7676                            + " due to specific " + specificsPos);
7677                        if (ri == null) {
7678                            ri = sri;
7679                        }
7680                        j--;
7681                        N--;
7682                    }
7683                }
7684
7685                // Add this specific item to its proper place.
7686                if (ri == null) {
7687                    ri = new ResolveInfo();
7688                    ri.activityInfo = ai;
7689                }
7690                results.add(specificsPos, ri);
7691                ri.specificIndex = i;
7692                specificsPos++;
7693            }
7694        }
7695
7696        // Now we go through the remaining generic results and remove any
7697        // duplicate actions that are found here.
7698        N = results.size();
7699        for (int i=specificsPos; i<N-1; i++) {
7700            final ResolveInfo rii = results.get(i);
7701            if (rii.filter == null) {
7702                continue;
7703            }
7704
7705            // Iterate over all of the actions of this result's intent
7706            // filter...  typically this should be just one.
7707            final Iterator<String> it = rii.filter.actionsIterator();
7708            if (it == null) {
7709                continue;
7710            }
7711            while (it.hasNext()) {
7712                final String action = it.next();
7713                if (resultsAction != null && resultsAction.equals(action)) {
7714                    // If this action was explicitly requested, then don't
7715                    // remove things that have it.
7716                    continue;
7717                }
7718                for (int j=i+1; j<N; j++) {
7719                    final ResolveInfo rij = results.get(j);
7720                    if (rij.filter != null && rij.filter.hasAction(action)) {
7721                        results.remove(j);
7722                        if (DEBUG_INTENT_MATCHING) Log.v(
7723                            TAG, "Removing duplicate item from " + j
7724                            + " due to action " + action + " at " + i);
7725                        j--;
7726                        N--;
7727                    }
7728                }
7729            }
7730
7731            // If the caller didn't request filter information, drop it now
7732            // so we don't have to marshall/unmarshall it.
7733            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7734                rii.filter = null;
7735            }
7736        }
7737
7738        // Filter out the caller activity if so requested.
7739        if (caller != null) {
7740            N = results.size();
7741            for (int i=0; i<N; i++) {
7742                ActivityInfo ainfo = results.get(i).activityInfo;
7743                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7744                        && caller.getClassName().equals(ainfo.name)) {
7745                    results.remove(i);
7746                    break;
7747                }
7748            }
7749        }
7750
7751        // If the caller didn't request filter information,
7752        // drop them now so we don't have to
7753        // marshall/unmarshall it.
7754        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7755            N = results.size();
7756            for (int i=0; i<N; i++) {
7757                results.get(i).filter = null;
7758            }
7759        }
7760
7761        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7762        return results;
7763    }
7764
7765    @Override
7766    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7767            String resolvedType, int flags, int userId) {
7768        return new ParceledListSlice<>(
7769                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7770    }
7771
7772    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7773            String resolvedType, int flags, int userId) {
7774        if (!sUserManager.exists(userId)) return Collections.emptyList();
7775        final int callingUid = Binder.getCallingUid();
7776        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7777        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7778                false /*includeInstantApps*/);
7779        ComponentName comp = intent.getComponent();
7780        if (comp == null) {
7781            if (intent.getSelector() != null) {
7782                intent = intent.getSelector();
7783                comp = intent.getComponent();
7784            }
7785        }
7786        if (comp != null) {
7787            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7788            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7789            if (ai != null) {
7790                // When specifying an explicit component, we prevent the activity from being
7791                // used when either 1) the calling package is normal and the activity is within
7792                // an instant application or 2) the calling package is ephemeral and the
7793                // activity is not visible to instant applications.
7794                final boolean matchInstantApp =
7795                        (flags & PackageManager.MATCH_INSTANT) != 0;
7796                final boolean matchVisibleToInstantAppOnly =
7797                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7798                final boolean matchExplicitlyVisibleOnly =
7799                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7800                final boolean isCallerInstantApp =
7801                        instantAppPkgName != null;
7802                final boolean isTargetSameInstantApp =
7803                        comp.getPackageName().equals(instantAppPkgName);
7804                final boolean isTargetInstantApp =
7805                        (ai.applicationInfo.privateFlags
7806                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7807                final boolean isTargetVisibleToInstantApp =
7808                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7809                final boolean isTargetExplicitlyVisibleToInstantApp =
7810                        isTargetVisibleToInstantApp
7811                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7812                final boolean isTargetHiddenFromInstantApp =
7813                        !isTargetVisibleToInstantApp
7814                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7815                final boolean blockResolution =
7816                        !isTargetSameInstantApp
7817                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7818                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7819                                        && isTargetHiddenFromInstantApp));
7820                if (!blockResolution) {
7821                    ResolveInfo ri = new ResolveInfo();
7822                    ri.activityInfo = ai;
7823                    list.add(ri);
7824                }
7825            }
7826            return applyPostResolutionFilter(list, instantAppPkgName);
7827        }
7828
7829        // reader
7830        synchronized (mPackages) {
7831            String pkgName = intent.getPackage();
7832            if (pkgName == null) {
7833                final List<ResolveInfo> result =
7834                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7835                return applyPostResolutionFilter(result, instantAppPkgName);
7836            }
7837            final PackageParser.Package pkg = mPackages.get(pkgName);
7838            if (pkg != null) {
7839                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7840                        intent, resolvedType, flags, pkg.receivers, userId);
7841                return applyPostResolutionFilter(result, instantAppPkgName);
7842            }
7843            return Collections.emptyList();
7844        }
7845    }
7846
7847    @Override
7848    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7849        final int callingUid = Binder.getCallingUid();
7850        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7851    }
7852
7853    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7854            int userId, int callingUid) {
7855        if (!sUserManager.exists(userId)) return null;
7856        flags = updateFlagsForResolve(
7857                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7858        List<ResolveInfo> query = queryIntentServicesInternal(
7859                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7860        if (query != null) {
7861            if (query.size() >= 1) {
7862                // If there is more than one service with the same priority,
7863                // just arbitrarily pick the first one.
7864                return query.get(0);
7865            }
7866        }
7867        return null;
7868    }
7869
7870    @Override
7871    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7872            String resolvedType, int flags, int userId) {
7873        final int callingUid = Binder.getCallingUid();
7874        return new ParceledListSlice<>(queryIntentServicesInternal(
7875                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7876    }
7877
7878    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7879            String resolvedType, int flags, int userId, int callingUid,
7880            boolean includeInstantApps) {
7881        if (!sUserManager.exists(userId)) return Collections.emptyList();
7882        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7883        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7884        ComponentName comp = intent.getComponent();
7885        if (comp == null) {
7886            if (intent.getSelector() != null) {
7887                intent = intent.getSelector();
7888                comp = intent.getComponent();
7889            }
7890        }
7891        if (comp != null) {
7892            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7893            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7894            if (si != null) {
7895                // When specifying an explicit component, we prevent the service from being
7896                // used when either 1) the service is in an instant application and the
7897                // caller is not the same instant application or 2) the calling package is
7898                // ephemeral and the activity is not visible to ephemeral applications.
7899                final boolean matchInstantApp =
7900                        (flags & PackageManager.MATCH_INSTANT) != 0;
7901                final boolean matchVisibleToInstantAppOnly =
7902                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7903                final boolean isCallerInstantApp =
7904                        instantAppPkgName != null;
7905                final boolean isTargetSameInstantApp =
7906                        comp.getPackageName().equals(instantAppPkgName);
7907                final boolean isTargetInstantApp =
7908                        (si.applicationInfo.privateFlags
7909                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7910                final boolean isTargetHiddenFromInstantApp =
7911                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7912                final boolean blockResolution =
7913                        !isTargetSameInstantApp
7914                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7915                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7916                                        && isTargetHiddenFromInstantApp));
7917                if (!blockResolution) {
7918                    final ResolveInfo ri = new ResolveInfo();
7919                    ri.serviceInfo = si;
7920                    list.add(ri);
7921                }
7922            }
7923            return list;
7924        }
7925
7926        // reader
7927        synchronized (mPackages) {
7928            String pkgName = intent.getPackage();
7929            if (pkgName == null) {
7930                return applyPostServiceResolutionFilter(
7931                        mServices.queryIntent(intent, resolvedType, flags, userId),
7932                        instantAppPkgName);
7933            }
7934            final PackageParser.Package pkg = mPackages.get(pkgName);
7935            if (pkg != null) {
7936                return applyPostServiceResolutionFilter(
7937                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7938                                userId),
7939                        instantAppPkgName);
7940            }
7941            return Collections.emptyList();
7942        }
7943    }
7944
7945    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7946            String instantAppPkgName) {
7947        // TODO: When adding on-demand split support for non-instant apps, remove this check
7948        // and always apply post filtering
7949        if (instantAppPkgName == null) {
7950            return resolveInfos;
7951        }
7952        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7953            final ResolveInfo info = resolveInfos.get(i);
7954            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7955            // allow services that are defined in the provided package
7956            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7957                if (info.serviceInfo.splitName != null
7958                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7959                                info.serviceInfo.splitName)) {
7960                    // requested service is defined in a split that hasn't been installed yet.
7961                    // add the installer to the resolve list
7962                    if (DEBUG_EPHEMERAL) {
7963                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7964                    }
7965                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7966                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7967                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7968                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7969                    // make sure this resolver is the default
7970                    installerInfo.isDefault = true;
7971                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7972                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7973                    // add a non-generic filter
7974                    installerInfo.filter = new IntentFilter();
7975                    // load resources from the correct package
7976                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7977                    resolveInfos.set(i, installerInfo);
7978                }
7979                continue;
7980            }
7981            // allow services that have been explicitly exposed to ephemeral apps
7982            if (!isEphemeralApp
7983                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7984                continue;
7985            }
7986            resolveInfos.remove(i);
7987        }
7988        return resolveInfos;
7989    }
7990
7991    @Override
7992    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7993            String resolvedType, int flags, int userId) {
7994        return new ParceledListSlice<>(
7995                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7996    }
7997
7998    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7999            Intent intent, String resolvedType, int flags, int userId) {
8000        if (!sUserManager.exists(userId)) return Collections.emptyList();
8001        final int callingUid = Binder.getCallingUid();
8002        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8003        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8004                false /*includeInstantApps*/);
8005        ComponentName comp = intent.getComponent();
8006        if (comp == null) {
8007            if (intent.getSelector() != null) {
8008                intent = intent.getSelector();
8009                comp = intent.getComponent();
8010            }
8011        }
8012        if (comp != null) {
8013            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8014            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8015            if (pi != null) {
8016                // When specifying an explicit component, we prevent the provider from being
8017                // used when either 1) the provider is in an instant application and the
8018                // caller is not the same instant application or 2) the calling package is an
8019                // instant application and the provider is not visible to instant applications.
8020                final boolean matchInstantApp =
8021                        (flags & PackageManager.MATCH_INSTANT) != 0;
8022                final boolean matchVisibleToInstantAppOnly =
8023                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8024                final boolean isCallerInstantApp =
8025                        instantAppPkgName != null;
8026                final boolean isTargetSameInstantApp =
8027                        comp.getPackageName().equals(instantAppPkgName);
8028                final boolean isTargetInstantApp =
8029                        (pi.applicationInfo.privateFlags
8030                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8031                final boolean isTargetHiddenFromInstantApp =
8032                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8033                final boolean blockResolution =
8034                        !isTargetSameInstantApp
8035                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8036                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8037                                        && isTargetHiddenFromInstantApp));
8038                if (!blockResolution) {
8039                    final ResolveInfo ri = new ResolveInfo();
8040                    ri.providerInfo = pi;
8041                    list.add(ri);
8042                }
8043            }
8044            return list;
8045        }
8046
8047        // reader
8048        synchronized (mPackages) {
8049            String pkgName = intent.getPackage();
8050            if (pkgName == null) {
8051                return applyPostContentProviderResolutionFilter(
8052                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8053                        instantAppPkgName);
8054            }
8055            final PackageParser.Package pkg = mPackages.get(pkgName);
8056            if (pkg != null) {
8057                return applyPostContentProviderResolutionFilter(
8058                        mProviders.queryIntentForPackage(
8059                        intent, resolvedType, flags, pkg.providers, userId),
8060                        instantAppPkgName);
8061            }
8062            return Collections.emptyList();
8063        }
8064    }
8065
8066    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8067            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8068        // TODO: When adding on-demand split support for non-instant applications, remove
8069        // this check and always apply post filtering
8070        if (instantAppPkgName == null) {
8071            return resolveInfos;
8072        }
8073        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8074            final ResolveInfo info = resolveInfos.get(i);
8075            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8076            // allow providers that are defined in the provided package
8077            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8078                if (info.providerInfo.splitName != null
8079                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8080                                info.providerInfo.splitName)) {
8081                    // requested provider is defined in a split that hasn't been installed yet.
8082                    // add the installer to the resolve list
8083                    if (DEBUG_EPHEMERAL) {
8084                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8085                    }
8086                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8087                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8088                            info.providerInfo.packageName, info.providerInfo.splitName,
8089                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8090                    // make sure this resolver is the default
8091                    installerInfo.isDefault = true;
8092                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8093                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8094                    // add a non-generic filter
8095                    installerInfo.filter = new IntentFilter();
8096                    // load resources from the correct package
8097                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8098                    resolveInfos.set(i, installerInfo);
8099                }
8100                continue;
8101            }
8102            // allow providers that have been explicitly exposed to instant applications
8103            if (!isEphemeralApp
8104                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8105                continue;
8106            }
8107            resolveInfos.remove(i);
8108        }
8109        return resolveInfos;
8110    }
8111
8112    @Override
8113    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8114        final int callingUid = Binder.getCallingUid();
8115        if (getInstantAppPackageName(callingUid) != null) {
8116            return ParceledListSlice.emptyList();
8117        }
8118        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8119        flags = updateFlagsForPackage(flags, userId, null);
8120        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8121        enforceCrossUserPermission(callingUid, userId,
8122                true /* requireFullPermission */, false /* checkShell */,
8123                "get installed packages");
8124
8125        // writer
8126        synchronized (mPackages) {
8127            ArrayList<PackageInfo> list;
8128            if (listUninstalled) {
8129                list = new ArrayList<>(mSettings.mPackages.size());
8130                for (PackageSetting ps : mSettings.mPackages.values()) {
8131                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8132                        continue;
8133                    }
8134                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8135                        return null;
8136                    }
8137                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8138                    if (pi != null) {
8139                        list.add(pi);
8140                    }
8141                }
8142            } else {
8143                list = new ArrayList<>(mPackages.size());
8144                for (PackageParser.Package p : mPackages.values()) {
8145                    final PackageSetting ps = (PackageSetting) p.mExtras;
8146                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8147                        continue;
8148                    }
8149                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8150                        return null;
8151                    }
8152                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8153                            p.mExtras, flags, userId);
8154                    if (pi != null) {
8155                        list.add(pi);
8156                    }
8157                }
8158            }
8159
8160            return new ParceledListSlice<>(list);
8161        }
8162    }
8163
8164    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8165            String[] permissions, boolean[] tmp, int flags, int userId) {
8166        int numMatch = 0;
8167        final PermissionsState permissionsState = ps.getPermissionsState();
8168        for (int i=0; i<permissions.length; i++) {
8169            final String permission = permissions[i];
8170            if (permissionsState.hasPermission(permission, userId)) {
8171                tmp[i] = true;
8172                numMatch++;
8173            } else {
8174                tmp[i] = false;
8175            }
8176        }
8177        if (numMatch == 0) {
8178            return;
8179        }
8180        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8181
8182        // The above might return null in cases of uninstalled apps or install-state
8183        // skew across users/profiles.
8184        if (pi != null) {
8185            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8186                if (numMatch == permissions.length) {
8187                    pi.requestedPermissions = permissions;
8188                } else {
8189                    pi.requestedPermissions = new String[numMatch];
8190                    numMatch = 0;
8191                    for (int i=0; i<permissions.length; i++) {
8192                        if (tmp[i]) {
8193                            pi.requestedPermissions[numMatch] = permissions[i];
8194                            numMatch++;
8195                        }
8196                    }
8197                }
8198            }
8199            list.add(pi);
8200        }
8201    }
8202
8203    @Override
8204    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8205            String[] permissions, int flags, int userId) {
8206        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8207        flags = updateFlagsForPackage(flags, userId, permissions);
8208        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8209                true /* requireFullPermission */, false /* checkShell */,
8210                "get packages holding permissions");
8211        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8212
8213        // writer
8214        synchronized (mPackages) {
8215            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8216            boolean[] tmpBools = new boolean[permissions.length];
8217            if (listUninstalled) {
8218                for (PackageSetting ps : mSettings.mPackages.values()) {
8219                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8220                            userId);
8221                }
8222            } else {
8223                for (PackageParser.Package pkg : mPackages.values()) {
8224                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8225                    if (ps != null) {
8226                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8227                                userId);
8228                    }
8229                }
8230            }
8231
8232            return new ParceledListSlice<PackageInfo>(list);
8233        }
8234    }
8235
8236    @Override
8237    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8238        final int callingUid = Binder.getCallingUid();
8239        if (getInstantAppPackageName(callingUid) != null) {
8240            return ParceledListSlice.emptyList();
8241        }
8242        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8243        flags = updateFlagsForApplication(flags, userId, null);
8244        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8245
8246        // writer
8247        synchronized (mPackages) {
8248            ArrayList<ApplicationInfo> list;
8249            if (listUninstalled) {
8250                list = new ArrayList<>(mSettings.mPackages.size());
8251                for (PackageSetting ps : mSettings.mPackages.values()) {
8252                    ApplicationInfo ai;
8253                    int effectiveFlags = flags;
8254                    if (ps.isSystem()) {
8255                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8256                    }
8257                    if (ps.pkg != null) {
8258                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8259                            continue;
8260                        }
8261                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8262                            return null;
8263                        }
8264                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8265                                ps.readUserState(userId), userId);
8266                        if (ai != null) {
8267                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8268                        }
8269                    } else {
8270                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8271                        // and already converts to externally visible package name
8272                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8273                                callingUid, effectiveFlags, userId);
8274                    }
8275                    if (ai != null) {
8276                        list.add(ai);
8277                    }
8278                }
8279            } else {
8280                list = new ArrayList<>(mPackages.size());
8281                for (PackageParser.Package p : mPackages.values()) {
8282                    if (p.mExtras != null) {
8283                        PackageSetting ps = (PackageSetting) p.mExtras;
8284                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8285                            continue;
8286                        }
8287                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8288                            return null;
8289                        }
8290                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8291                                ps.readUserState(userId), userId);
8292                        if (ai != null) {
8293                            ai.packageName = resolveExternalPackageNameLPr(p);
8294                            list.add(ai);
8295                        }
8296                    }
8297                }
8298            }
8299
8300            return new ParceledListSlice<>(list);
8301        }
8302    }
8303
8304    @Override
8305    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8306        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8307            return null;
8308        }
8309        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8310                "getEphemeralApplications");
8311        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8312                true /* requireFullPermission */, false /* checkShell */,
8313                "getEphemeralApplications");
8314        synchronized (mPackages) {
8315            List<InstantAppInfo> instantApps = mInstantAppRegistry
8316                    .getInstantAppsLPr(userId);
8317            if (instantApps != null) {
8318                return new ParceledListSlice<>(instantApps);
8319            }
8320        }
8321        return null;
8322    }
8323
8324    @Override
8325    public boolean isInstantApp(String packageName, int userId) {
8326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8327                true /* requireFullPermission */, false /* checkShell */,
8328                "isInstantApp");
8329        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8330            return false;
8331        }
8332        int callingUid = Binder.getCallingUid();
8333        if (Process.isIsolated(callingUid)) {
8334            callingUid = mIsolatedOwners.get(callingUid);
8335        }
8336
8337        synchronized (mPackages) {
8338            final PackageSetting ps = mSettings.mPackages.get(packageName);
8339            PackageParser.Package pkg = mPackages.get(packageName);
8340            final boolean returnAllowed =
8341                    ps != null
8342                    && (isCallerSameApp(packageName, callingUid)
8343                            || canViewInstantApps(callingUid, userId)
8344                            || mInstantAppRegistry.isInstantAccessGranted(
8345                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8346            if (returnAllowed) {
8347                return ps.getInstantApp(userId);
8348            }
8349        }
8350        return false;
8351    }
8352
8353    @Override
8354    public byte[] getInstantAppCookie(String packageName, int userId) {
8355        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8356            return null;
8357        }
8358
8359        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8360                true /* requireFullPermission */, false /* checkShell */,
8361                "getInstantAppCookie");
8362        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8363            return null;
8364        }
8365        synchronized (mPackages) {
8366            return mInstantAppRegistry.getInstantAppCookieLPw(
8367                    packageName, userId);
8368        }
8369    }
8370
8371    @Override
8372    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8373        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8374            return true;
8375        }
8376
8377        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8378                true /* requireFullPermission */, true /* checkShell */,
8379                "setInstantAppCookie");
8380        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8381            return false;
8382        }
8383        synchronized (mPackages) {
8384            return mInstantAppRegistry.setInstantAppCookieLPw(
8385                    packageName, cookie, userId);
8386        }
8387    }
8388
8389    @Override
8390    public Bitmap getInstantAppIcon(String packageName, int userId) {
8391        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8392            return null;
8393        }
8394
8395        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8396                "getInstantAppIcon");
8397
8398        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8399                true /* requireFullPermission */, false /* checkShell */,
8400                "getInstantAppIcon");
8401
8402        synchronized (mPackages) {
8403            return mInstantAppRegistry.getInstantAppIconLPw(
8404                    packageName, userId);
8405        }
8406    }
8407
8408    private boolean isCallerSameApp(String packageName, int uid) {
8409        PackageParser.Package pkg = mPackages.get(packageName);
8410        return pkg != null
8411                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8412    }
8413
8414    @Override
8415    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8416        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8417            return ParceledListSlice.emptyList();
8418        }
8419        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8420    }
8421
8422    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8423        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8424
8425        // reader
8426        synchronized (mPackages) {
8427            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8428            final int userId = UserHandle.getCallingUserId();
8429            while (i.hasNext()) {
8430                final PackageParser.Package p = i.next();
8431                if (p.applicationInfo == null) continue;
8432
8433                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8434                        && !p.applicationInfo.isDirectBootAware();
8435                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8436                        && p.applicationInfo.isDirectBootAware();
8437
8438                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8439                        && (!mSafeMode || isSystemApp(p))
8440                        && (matchesUnaware || matchesAware)) {
8441                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8442                    if (ps != null) {
8443                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8444                                ps.readUserState(userId), userId);
8445                        if (ai != null) {
8446                            finalList.add(ai);
8447                        }
8448                    }
8449                }
8450            }
8451        }
8452
8453        return finalList;
8454    }
8455
8456    @Override
8457    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8458        if (!sUserManager.exists(userId)) return null;
8459        flags = updateFlagsForComponent(flags, userId, name);
8460        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8461        // reader
8462        synchronized (mPackages) {
8463            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8464            PackageSetting ps = provider != null
8465                    ? mSettings.mPackages.get(provider.owner.packageName)
8466                    : null;
8467            if (ps != null) {
8468                final boolean isInstantApp = ps.getInstantApp(userId);
8469                // normal application; filter out instant application provider
8470                if (instantAppPkgName == null && isInstantApp) {
8471                    return null;
8472                }
8473                // instant application; filter out other instant applications
8474                if (instantAppPkgName != null
8475                        && isInstantApp
8476                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8477                    return null;
8478                }
8479                // instant application; filter out non-exposed provider
8480                if (instantAppPkgName != null
8481                        && !isInstantApp
8482                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8483                    return null;
8484                }
8485                // provider not enabled
8486                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8487                    return null;
8488                }
8489                return PackageParser.generateProviderInfo(
8490                        provider, flags, ps.readUserState(userId), userId);
8491            }
8492            return null;
8493        }
8494    }
8495
8496    /**
8497     * @deprecated
8498     */
8499    @Deprecated
8500    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8501        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8502            return;
8503        }
8504        // reader
8505        synchronized (mPackages) {
8506            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8507                    .entrySet().iterator();
8508            final int userId = UserHandle.getCallingUserId();
8509            while (i.hasNext()) {
8510                Map.Entry<String, PackageParser.Provider> entry = i.next();
8511                PackageParser.Provider p = entry.getValue();
8512                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8513
8514                if (ps != null && p.syncable
8515                        && (!mSafeMode || (p.info.applicationInfo.flags
8516                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8517                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8518                            ps.readUserState(userId), userId);
8519                    if (info != null) {
8520                        outNames.add(entry.getKey());
8521                        outInfo.add(info);
8522                    }
8523                }
8524            }
8525        }
8526    }
8527
8528    @Override
8529    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8530            int uid, int flags, String metaDataKey) {
8531        final int callingUid = Binder.getCallingUid();
8532        final int userId = processName != null ? UserHandle.getUserId(uid)
8533                : UserHandle.getCallingUserId();
8534        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8535        flags = updateFlagsForComponent(flags, userId, processName);
8536        ArrayList<ProviderInfo> finalList = null;
8537        // reader
8538        synchronized (mPackages) {
8539            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8540            while (i.hasNext()) {
8541                final PackageParser.Provider p = i.next();
8542                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8543                if (ps != null && p.info.authority != null
8544                        && (processName == null
8545                                || (p.info.processName.equals(processName)
8546                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8547                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8548
8549                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8550                    // parameter.
8551                    if (metaDataKey != null
8552                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8553                        continue;
8554                    }
8555                    final ComponentName component =
8556                            new ComponentName(p.info.packageName, p.info.name);
8557                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8558                        continue;
8559                    }
8560                    if (finalList == null) {
8561                        finalList = new ArrayList<ProviderInfo>(3);
8562                    }
8563                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8564                            ps.readUserState(userId), userId);
8565                    if (info != null) {
8566                        finalList.add(info);
8567                    }
8568                }
8569            }
8570        }
8571
8572        if (finalList != null) {
8573            Collections.sort(finalList, mProviderInitOrderSorter);
8574            return new ParceledListSlice<ProviderInfo>(finalList);
8575        }
8576
8577        return ParceledListSlice.emptyList();
8578    }
8579
8580    @Override
8581    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8582        // reader
8583        synchronized (mPackages) {
8584            final int callingUid = Binder.getCallingUid();
8585            final int callingUserId = UserHandle.getUserId(callingUid);
8586            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8587            if (ps == null) return null;
8588            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8589                return null;
8590            }
8591            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8592            return PackageParser.generateInstrumentationInfo(i, flags);
8593        }
8594    }
8595
8596    @Override
8597    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8598            String targetPackage, int flags) {
8599        final int callingUid = Binder.getCallingUid();
8600        final int callingUserId = UserHandle.getUserId(callingUid);
8601        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8602        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8603            return ParceledListSlice.emptyList();
8604        }
8605        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8606    }
8607
8608    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8609            int flags) {
8610        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8611
8612        // reader
8613        synchronized (mPackages) {
8614            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8615            while (i.hasNext()) {
8616                final PackageParser.Instrumentation p = i.next();
8617                if (targetPackage == null
8618                        || targetPackage.equals(p.info.targetPackage)) {
8619                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8620                            flags);
8621                    if (ii != null) {
8622                        finalList.add(ii);
8623                    }
8624                }
8625            }
8626        }
8627
8628        return finalList;
8629    }
8630
8631    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8632        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8633        try {
8634            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8635        } finally {
8636            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8637        }
8638    }
8639
8640    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8641        final File[] files = dir.listFiles();
8642        if (ArrayUtils.isEmpty(files)) {
8643            Log.d(TAG, "No files in app dir " + dir);
8644            return;
8645        }
8646
8647        if (DEBUG_PACKAGE_SCANNING) {
8648            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8649                    + " flags=0x" + Integer.toHexString(parseFlags));
8650        }
8651        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8652                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8653                mParallelPackageParserCallback);
8654
8655        // Submit files for parsing in parallel
8656        int fileCount = 0;
8657        for (File file : files) {
8658            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8659                    && !PackageInstallerService.isStageName(file.getName());
8660            if (!isPackage) {
8661                // Ignore entries which are not packages
8662                continue;
8663            }
8664            parallelPackageParser.submit(file, parseFlags);
8665            fileCount++;
8666        }
8667
8668        // Process results one by one
8669        for (; fileCount > 0; fileCount--) {
8670            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8671            Throwable throwable = parseResult.throwable;
8672            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8673
8674            if (throwable == null) {
8675                // Static shared libraries have synthetic package names
8676                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8677                    renameStaticSharedLibraryPackage(parseResult.pkg);
8678                }
8679                try {
8680                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8681                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8682                                currentTime, null);
8683                    }
8684                } catch (PackageManagerException e) {
8685                    errorCode = e.error;
8686                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8687                }
8688            } else if (throwable instanceof PackageParser.PackageParserException) {
8689                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8690                        throwable;
8691                errorCode = e.error;
8692                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8693            } else {
8694                throw new IllegalStateException("Unexpected exception occurred while parsing "
8695                        + parseResult.scanFile, throwable);
8696            }
8697
8698            // Delete invalid userdata apps
8699            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8700                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8701                logCriticalInfo(Log.WARN,
8702                        "Deleting invalid package at " + parseResult.scanFile);
8703                removeCodePathLI(parseResult.scanFile);
8704            }
8705        }
8706        parallelPackageParser.close();
8707    }
8708
8709    private static File getSettingsProblemFile() {
8710        File dataDir = Environment.getDataDirectory();
8711        File systemDir = new File(dataDir, "system");
8712        File fname = new File(systemDir, "uiderrors.txt");
8713        return fname;
8714    }
8715
8716    static void reportSettingsProblem(int priority, String msg) {
8717        logCriticalInfo(priority, msg);
8718    }
8719
8720    public static void logCriticalInfo(int priority, String msg) {
8721        Slog.println(priority, TAG, msg);
8722        EventLogTags.writePmCriticalInfo(msg);
8723        try {
8724            File fname = getSettingsProblemFile();
8725            FileOutputStream out = new FileOutputStream(fname, true);
8726            PrintWriter pw = new FastPrintWriter(out);
8727            SimpleDateFormat formatter = new SimpleDateFormat();
8728            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8729            pw.println(dateString + ": " + msg);
8730            pw.close();
8731            FileUtils.setPermissions(
8732                    fname.toString(),
8733                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8734                    -1, -1);
8735        } catch (java.io.IOException e) {
8736        }
8737    }
8738
8739    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8740        if (srcFile.isDirectory()) {
8741            final File baseFile = new File(pkg.baseCodePath);
8742            long maxModifiedTime = baseFile.lastModified();
8743            if (pkg.splitCodePaths != null) {
8744                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8745                    final File splitFile = new File(pkg.splitCodePaths[i]);
8746                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8747                }
8748            }
8749            return maxModifiedTime;
8750        }
8751        return srcFile.lastModified();
8752    }
8753
8754    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8755            final int policyFlags) throws PackageManagerException {
8756        // When upgrading from pre-N MR1, verify the package time stamp using the package
8757        // directory and not the APK file.
8758        final long lastModifiedTime = mIsPreNMR1Upgrade
8759                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8760        if (ps != null
8761                && ps.codePath.equals(srcFile)
8762                && ps.timeStamp == lastModifiedTime
8763                && !isCompatSignatureUpdateNeeded(pkg)
8764                && !isRecoverSignatureUpdateNeeded(pkg)) {
8765            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8766            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8767            ArraySet<PublicKey> signingKs;
8768            synchronized (mPackages) {
8769                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8770            }
8771            if (ps.signatures.mSignatures != null
8772                    && ps.signatures.mSignatures.length != 0
8773                    && signingKs != null) {
8774                // Optimization: reuse the existing cached certificates
8775                // if the package appears to be unchanged.
8776                pkg.mSignatures = ps.signatures.mSignatures;
8777                pkg.mSigningKeys = signingKs;
8778                return;
8779            }
8780
8781            Slog.w(TAG, "PackageSetting for " + ps.name
8782                    + " is missing signatures.  Collecting certs again to recover them.");
8783        } else {
8784            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8785        }
8786
8787        try {
8788            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8789            PackageParser.collectCertificates(pkg, policyFlags);
8790        } catch (PackageParserException e) {
8791            throw PackageManagerException.from(e);
8792        } finally {
8793            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8794        }
8795    }
8796
8797    /**
8798     *  Traces a package scan.
8799     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8800     */
8801    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8802            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8803        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8804        try {
8805            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8806        } finally {
8807            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8808        }
8809    }
8810
8811    /**
8812     *  Scans a package and returns the newly parsed package.
8813     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8814     */
8815    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8816            long currentTime, UserHandle user) throws PackageManagerException {
8817        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8818        PackageParser pp = new PackageParser();
8819        pp.setSeparateProcesses(mSeparateProcesses);
8820        pp.setOnlyCoreApps(mOnlyCore);
8821        pp.setDisplayMetrics(mMetrics);
8822        pp.setCallback(mPackageParserCallback);
8823
8824        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8825            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8826        }
8827
8828        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8829        final PackageParser.Package pkg;
8830        try {
8831            pkg = pp.parsePackage(scanFile, parseFlags);
8832        } catch (PackageParserException e) {
8833            throw PackageManagerException.from(e);
8834        } finally {
8835            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8836        }
8837
8838        // Static shared libraries have synthetic package names
8839        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8840            renameStaticSharedLibraryPackage(pkg);
8841        }
8842
8843        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8844    }
8845
8846    /**
8847     *  Scans a package and returns the newly parsed package.
8848     *  @throws PackageManagerException on a parse error.
8849     */
8850    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8851            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8852            throws PackageManagerException {
8853        // If the package has children and this is the first dive in the function
8854        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8855        // packages (parent and children) would be successfully scanned before the
8856        // actual scan since scanning mutates internal state and we want to atomically
8857        // install the package and its children.
8858        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8859            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8860                scanFlags |= SCAN_CHECK_ONLY;
8861            }
8862        } else {
8863            scanFlags &= ~SCAN_CHECK_ONLY;
8864        }
8865
8866        // Scan the parent
8867        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8868                scanFlags, currentTime, user);
8869
8870        // Scan the children
8871        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8872        for (int i = 0; i < childCount; i++) {
8873            PackageParser.Package childPackage = pkg.childPackages.get(i);
8874            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8875                    currentTime, user);
8876        }
8877
8878
8879        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8880            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8881        }
8882
8883        return scannedPkg;
8884    }
8885
8886    /**
8887     *  Scans a package and returns the newly parsed package.
8888     *  @throws PackageManagerException on a parse error.
8889     */
8890    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8891            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8892            throws PackageManagerException {
8893        PackageSetting ps = null;
8894        PackageSetting updatedPkg;
8895        // reader
8896        synchronized (mPackages) {
8897            // Look to see if we already know about this package.
8898            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8899            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8900                // This package has been renamed to its original name.  Let's
8901                // use that.
8902                ps = mSettings.getPackageLPr(oldName);
8903            }
8904            // If there was no original package, see one for the real package name.
8905            if (ps == null) {
8906                ps = mSettings.getPackageLPr(pkg.packageName);
8907            }
8908            // Check to see if this package could be hiding/updating a system
8909            // package.  Must look for it either under the original or real
8910            // package name depending on our state.
8911            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8912            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8913
8914            // If this is a package we don't know about on the system partition, we
8915            // may need to remove disabled child packages on the system partition
8916            // or may need to not add child packages if the parent apk is updated
8917            // on the data partition and no longer defines this child package.
8918            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8919                // If this is a parent package for an updated system app and this system
8920                // app got an OTA update which no longer defines some of the child packages
8921                // we have to prune them from the disabled system packages.
8922                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8923                if (disabledPs != null) {
8924                    final int scannedChildCount = (pkg.childPackages != null)
8925                            ? pkg.childPackages.size() : 0;
8926                    final int disabledChildCount = disabledPs.childPackageNames != null
8927                            ? disabledPs.childPackageNames.size() : 0;
8928                    for (int i = 0; i < disabledChildCount; i++) {
8929                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8930                        boolean disabledPackageAvailable = false;
8931                        for (int j = 0; j < scannedChildCount; j++) {
8932                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8933                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8934                                disabledPackageAvailable = true;
8935                                break;
8936                            }
8937                         }
8938                         if (!disabledPackageAvailable) {
8939                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8940                         }
8941                    }
8942                }
8943            }
8944        }
8945
8946        final boolean isUpdatedPkg = updatedPkg != null;
8947        final boolean isUpdatedSystemPkg = isUpdatedPkg
8948                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8949        boolean isUpdatedPkgBetter = false;
8950        // First check if this is a system package that may involve an update
8951        if (isUpdatedSystemPkg) {
8952            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8953            // it needs to drop FLAG_PRIVILEGED.
8954            if (locationIsPrivileged(scanFile)) {
8955                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8956            } else {
8957                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8958            }
8959
8960            if (ps != null && !ps.codePath.equals(scanFile)) {
8961                // The path has changed from what was last scanned...  check the
8962                // version of the new path against what we have stored to determine
8963                // what to do.
8964                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8965                if (pkg.mVersionCode <= ps.versionCode) {
8966                    // The system package has been updated and the code path does not match
8967                    // Ignore entry. Skip it.
8968                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8969                            + " ignored: updated version " + ps.versionCode
8970                            + " better than this " + pkg.mVersionCode);
8971                    if (!updatedPkg.codePath.equals(scanFile)) {
8972                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8973                                + ps.name + " changing from " + updatedPkg.codePathString
8974                                + " to " + scanFile);
8975                        updatedPkg.codePath = scanFile;
8976                        updatedPkg.codePathString = scanFile.toString();
8977                        updatedPkg.resourcePath = scanFile;
8978                        updatedPkg.resourcePathString = scanFile.toString();
8979                    }
8980                    updatedPkg.pkg = pkg;
8981                    updatedPkg.versionCode = pkg.mVersionCode;
8982
8983                    // Update the disabled system child packages to point to the package too.
8984                    final int childCount = updatedPkg.childPackageNames != null
8985                            ? updatedPkg.childPackageNames.size() : 0;
8986                    for (int i = 0; i < childCount; i++) {
8987                        String childPackageName = updatedPkg.childPackageNames.get(i);
8988                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8989                                childPackageName);
8990                        if (updatedChildPkg != null) {
8991                            updatedChildPkg.pkg = pkg;
8992                            updatedChildPkg.versionCode = pkg.mVersionCode;
8993                        }
8994                    }
8995                } else {
8996                    // The current app on the system partition is better than
8997                    // what we have updated to on the data partition; switch
8998                    // back to the system partition version.
8999                    // At this point, its safely assumed that package installation for
9000                    // apps in system partition will go through. If not there won't be a working
9001                    // version of the app
9002                    // writer
9003                    synchronized (mPackages) {
9004                        // Just remove the loaded entries from package lists.
9005                        mPackages.remove(ps.name);
9006                    }
9007
9008                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9009                            + " reverting from " + ps.codePathString
9010                            + ": new version " + pkg.mVersionCode
9011                            + " better than installed " + ps.versionCode);
9012
9013                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9014                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9015                    synchronized (mInstallLock) {
9016                        args.cleanUpResourcesLI();
9017                    }
9018                    synchronized (mPackages) {
9019                        mSettings.enableSystemPackageLPw(ps.name);
9020                    }
9021                    isUpdatedPkgBetter = true;
9022                }
9023            }
9024        }
9025
9026        String resourcePath = null;
9027        String baseResourcePath = null;
9028        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9029            if (ps != null && ps.resourcePathString != null) {
9030                resourcePath = ps.resourcePathString;
9031                baseResourcePath = ps.resourcePathString;
9032            } else {
9033                // Should not happen at all. Just log an error.
9034                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9035            }
9036        } else {
9037            resourcePath = pkg.codePath;
9038            baseResourcePath = pkg.baseCodePath;
9039        }
9040
9041        // Set application objects path explicitly.
9042        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9043        pkg.setApplicationInfoCodePath(pkg.codePath);
9044        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9045        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9046        pkg.setApplicationInfoResourcePath(resourcePath);
9047        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9048        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9049
9050        // throw an exception if we have an update to a system application, but, it's not more
9051        // recent than the package we've already scanned
9052        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9053            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9054                    + scanFile + " ignored: updated version " + ps.versionCode
9055                    + " better than this " + pkg.mVersionCode);
9056        }
9057
9058        if (isUpdatedPkg) {
9059            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9060            // initially
9061            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9062
9063            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9064            // flag set initially
9065            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9066                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9067            }
9068        }
9069
9070        // Verify certificates against what was last scanned
9071        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9072
9073        /*
9074         * A new system app appeared, but we already had a non-system one of the
9075         * same name installed earlier.
9076         */
9077        boolean shouldHideSystemApp = false;
9078        if (!isUpdatedPkg && ps != null
9079                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9080            /*
9081             * Check to make sure the signatures match first. If they don't,
9082             * wipe the installed application and its data.
9083             */
9084            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9085                    != PackageManager.SIGNATURE_MATCH) {
9086                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9087                        + " signatures don't match existing userdata copy; removing");
9088                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9089                        "scanPackageInternalLI")) {
9090                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9091                }
9092                ps = null;
9093            } else {
9094                /*
9095                 * If the newly-added system app is an older version than the
9096                 * already installed version, hide it. It will be scanned later
9097                 * and re-added like an update.
9098                 */
9099                if (pkg.mVersionCode <= ps.versionCode) {
9100                    shouldHideSystemApp = true;
9101                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9102                            + " but new version " + pkg.mVersionCode + " better than installed "
9103                            + ps.versionCode + "; hiding system");
9104                } else {
9105                    /*
9106                     * The newly found system app is a newer version that the
9107                     * one previously installed. Simply remove the
9108                     * already-installed application and replace it with our own
9109                     * while keeping the application data.
9110                     */
9111                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9112                            + " reverting from " + ps.codePathString + ": new version "
9113                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9114                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9115                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9116                    synchronized (mInstallLock) {
9117                        args.cleanUpResourcesLI();
9118                    }
9119                }
9120            }
9121        }
9122
9123        // The apk is forward locked (not public) if its code and resources
9124        // are kept in different files. (except for app in either system or
9125        // vendor path).
9126        // TODO grab this value from PackageSettings
9127        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9128            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9129                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9130            }
9131        }
9132
9133        final int userId = ((user == null) ? 0 : user.getIdentifier());
9134        if (ps != null && ps.getInstantApp(userId)) {
9135            scanFlags |= SCAN_AS_INSTANT_APP;
9136        }
9137
9138        // Note that we invoke the following method only if we are about to unpack an application
9139        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9140                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9141
9142        /*
9143         * If the system app should be overridden by a previously installed
9144         * data, hide the system app now and let the /data/app scan pick it up
9145         * again.
9146         */
9147        if (shouldHideSystemApp) {
9148            synchronized (mPackages) {
9149                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9150            }
9151        }
9152
9153        return scannedPkg;
9154    }
9155
9156    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9157        // Derive the new package synthetic package name
9158        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9159                + pkg.staticSharedLibVersion);
9160    }
9161
9162    private static String fixProcessName(String defProcessName,
9163            String processName) {
9164        if (processName == null) {
9165            return defProcessName;
9166        }
9167        return processName;
9168    }
9169
9170    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9171            throws PackageManagerException {
9172        if (pkgSetting.signatures.mSignatures != null) {
9173            // Already existing package. Make sure signatures match
9174            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9175                    == PackageManager.SIGNATURE_MATCH;
9176            if (!match) {
9177                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9178                        == PackageManager.SIGNATURE_MATCH;
9179            }
9180            if (!match) {
9181                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9182                        == PackageManager.SIGNATURE_MATCH;
9183            }
9184            if (!match) {
9185                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9186                        + pkg.packageName + " signatures do not match the "
9187                        + "previously installed version; ignoring!");
9188            }
9189        }
9190
9191        // Check for shared user signatures
9192        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9193            // Already existing package. Make sure signatures match
9194            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9195                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9196            if (!match) {
9197                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9198                        == PackageManager.SIGNATURE_MATCH;
9199            }
9200            if (!match) {
9201                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9202                        == PackageManager.SIGNATURE_MATCH;
9203            }
9204            if (!match) {
9205                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9206                        "Package " + pkg.packageName
9207                        + " has no signatures that match those in shared user "
9208                        + pkgSetting.sharedUser.name + "; ignoring!");
9209            }
9210        }
9211    }
9212
9213    /**
9214     * Enforces that only the system UID or root's UID can call a method exposed
9215     * via Binder.
9216     *
9217     * @param message used as message if SecurityException is thrown
9218     * @throws SecurityException if the caller is not system or root
9219     */
9220    private static final void enforceSystemOrRoot(String message) {
9221        final int uid = Binder.getCallingUid();
9222        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9223            throw new SecurityException(message);
9224        }
9225    }
9226
9227    @Override
9228    public void performFstrimIfNeeded() {
9229        enforceSystemOrRoot("Only the system can request fstrim");
9230
9231        // Before everything else, see whether we need to fstrim.
9232        try {
9233            IStorageManager sm = PackageHelper.getStorageManager();
9234            if (sm != null) {
9235                boolean doTrim = false;
9236                final long interval = android.provider.Settings.Global.getLong(
9237                        mContext.getContentResolver(),
9238                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9239                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9240                if (interval > 0) {
9241                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9242                    if (timeSinceLast > interval) {
9243                        doTrim = true;
9244                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9245                                + "; running immediately");
9246                    }
9247                }
9248                if (doTrim) {
9249                    final boolean dexOptDialogShown;
9250                    synchronized (mPackages) {
9251                        dexOptDialogShown = mDexOptDialogShown;
9252                    }
9253                    if (!isFirstBoot() && dexOptDialogShown) {
9254                        try {
9255                            ActivityManager.getService().showBootMessage(
9256                                    mContext.getResources().getString(
9257                                            R.string.android_upgrading_fstrim), true);
9258                        } catch (RemoteException e) {
9259                        }
9260                    }
9261                    sm.runMaintenance();
9262                }
9263            } else {
9264                Slog.e(TAG, "storageManager service unavailable!");
9265            }
9266        } catch (RemoteException e) {
9267            // Can't happen; StorageManagerService is local
9268        }
9269    }
9270
9271    @Override
9272    public void updatePackagesIfNeeded() {
9273        enforceSystemOrRoot("Only the system can request package update");
9274
9275        // We need to re-extract after an OTA.
9276        boolean causeUpgrade = isUpgrade();
9277
9278        // First boot or factory reset.
9279        // Note: we also handle devices that are upgrading to N right now as if it is their
9280        //       first boot, as they do not have profile data.
9281        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9282
9283        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9284        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9285
9286        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9287            return;
9288        }
9289
9290        List<PackageParser.Package> pkgs;
9291        synchronized (mPackages) {
9292            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9293        }
9294
9295        final long startTime = System.nanoTime();
9296        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9297                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9298                    false /* bootComplete */);
9299
9300        final int elapsedTimeSeconds =
9301                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9302
9303        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9304        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9305        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9306        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9307        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9308    }
9309
9310    /*
9311     * Return the prebuilt profile path given a package base code path.
9312     */
9313    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9314        return pkg.baseCodePath + ".prof";
9315    }
9316
9317    /**
9318     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9319     * containing statistics about the invocation. The array consists of three elements,
9320     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9321     * and {@code numberOfPackagesFailed}.
9322     */
9323    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9324            String compilerFilter, boolean bootComplete) {
9325
9326        int numberOfPackagesVisited = 0;
9327        int numberOfPackagesOptimized = 0;
9328        int numberOfPackagesSkipped = 0;
9329        int numberOfPackagesFailed = 0;
9330        final int numberOfPackagesToDexopt = pkgs.size();
9331
9332        for (PackageParser.Package pkg : pkgs) {
9333            numberOfPackagesVisited++;
9334
9335            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9336                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9337                // that are already compiled.
9338                File profileFile = new File(getPrebuildProfilePath(pkg));
9339                // Copy profile if it exists.
9340                if (profileFile.exists()) {
9341                    try {
9342                        // We could also do this lazily before calling dexopt in
9343                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9344                        // is that we don't have a good way to say "do this only once".
9345                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9346                                pkg.applicationInfo.uid, pkg.packageName)) {
9347                            Log.e(TAG, "Installer failed to copy system profile!");
9348                        }
9349                    } catch (Exception e) {
9350                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9351                                e);
9352                    }
9353                }
9354            }
9355
9356            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9357                if (DEBUG_DEXOPT) {
9358                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9359                }
9360                numberOfPackagesSkipped++;
9361                continue;
9362            }
9363
9364            if (DEBUG_DEXOPT) {
9365                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9366                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9367            }
9368
9369            if (showDialog) {
9370                try {
9371                    ActivityManager.getService().showBootMessage(
9372                            mContext.getResources().getString(R.string.android_upgrading_apk,
9373                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9374                } catch (RemoteException e) {
9375                }
9376                synchronized (mPackages) {
9377                    mDexOptDialogShown = true;
9378                }
9379            }
9380
9381            // If the OTA updates a system app which was previously preopted to a non-preopted state
9382            // the app might end up being verified at runtime. That's because by default the apps
9383            // are verify-profile but for preopted apps there's no profile.
9384            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9385            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9386            // filter (by default 'quicken').
9387            // Note that at this stage unused apps are already filtered.
9388            if (isSystemApp(pkg) &&
9389                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9390                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9391                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9392            }
9393
9394            // checkProfiles is false to avoid merging profiles during boot which
9395            // might interfere with background compilation (b/28612421).
9396            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9397            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9398            // trade-off worth doing to save boot time work.
9399            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9400            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9401                    pkg.packageName,
9402                    compilerFilter,
9403                    dexoptFlags));
9404
9405            boolean secondaryDexOptStatus = true;
9406            if (pkg.isSystemApp()) {
9407                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9408                // too much boot after an OTA.
9409                int secondaryDexoptFlags = dexoptFlags |
9410                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9411                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9412                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9413                        pkg.packageName,
9414                        compilerFilter,
9415                        secondaryDexoptFlags));
9416            }
9417
9418            if (secondaryDexOptStatus) {
9419                switch (primaryDexOptStaus) {
9420                    case PackageDexOptimizer.DEX_OPT_PERFORMED:
9421                        numberOfPackagesOptimized++;
9422                        break;
9423                    case PackageDexOptimizer.DEX_OPT_SKIPPED:
9424                        numberOfPackagesSkipped++;
9425                        break;
9426                    case PackageDexOptimizer.DEX_OPT_FAILED:
9427                        numberOfPackagesFailed++;
9428                        break;
9429                    default:
9430                        Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9431                        break;
9432                }
9433            } else {
9434                numberOfPackagesFailed++;
9435            }
9436        }
9437
9438        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9439                numberOfPackagesFailed };
9440    }
9441
9442    @Override
9443    public void notifyPackageUse(String packageName, int reason) {
9444        synchronized (mPackages) {
9445            final int callingUid = Binder.getCallingUid();
9446            final int callingUserId = UserHandle.getUserId(callingUid);
9447            if (getInstantAppPackageName(callingUid) != null) {
9448                if (!isCallerSameApp(packageName, callingUid)) {
9449                    return;
9450                }
9451            } else {
9452                if (isInstantApp(packageName, callingUserId)) {
9453                    return;
9454                }
9455            }
9456            final PackageParser.Package p = mPackages.get(packageName);
9457            if (p == null) {
9458                return;
9459            }
9460            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9461        }
9462    }
9463
9464    @Override
9465    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9466            List<String> classPaths, String loaderIsa) {
9467        int userId = UserHandle.getCallingUserId();
9468        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9469        if (ai == null) {
9470            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9471                + loadingPackageName + ", user=" + userId);
9472            return;
9473        }
9474        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9475    }
9476
9477    @Override
9478    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9479            IDexModuleRegisterCallback callback) {
9480        int userId = UserHandle.getCallingUserId();
9481        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9482        DexManager.RegisterDexModuleResult result;
9483        if (ai == null) {
9484            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9485                     " calling user. package=" + packageName + ", user=" + userId);
9486            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9487        } else {
9488            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9489        }
9490
9491        if (callback != null) {
9492            mHandler.post(() -> {
9493                try {
9494                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9495                } catch (RemoteException e) {
9496                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9497                }
9498            });
9499        }
9500    }
9501
9502    /**
9503     * Ask the package manager to perform a dex-opt with the given compiler filter.
9504     *
9505     * Note: exposed only for the shell command to allow moving packages explicitly to a
9506     *       definite state.
9507     */
9508    @Override
9509    public boolean performDexOptMode(String packageName,
9510            boolean checkProfiles, String targetCompilerFilter, boolean force,
9511            boolean bootComplete, String splitName) {
9512        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9513                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9514                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9515        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9516                splitName, flags));
9517    }
9518
9519    /**
9520     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9521     * secondary dex files belonging to the given package.
9522     *
9523     * Note: exposed only for the shell command to allow moving packages explicitly to a
9524     *       definite state.
9525     */
9526    @Override
9527    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9528            boolean force) {
9529        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9530                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9531                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9532                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9533        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9534    }
9535
9536    /*package*/ boolean performDexOpt(DexoptOptions options) {
9537        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9538            return false;
9539        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9540            return false;
9541        }
9542
9543        if (options.isDexoptOnlySecondaryDex()) {
9544            return mDexManager.dexoptSecondaryDex(options);
9545        } else {
9546            int dexoptStatus = performDexOptWithStatus(options);
9547            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9548        }
9549    }
9550
9551    /**
9552     * Perform dexopt on the given package and return one of following result:
9553     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9554     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9555     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9556     */
9557    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9558        return performDexOptTraced(options);
9559    }
9560
9561    private int performDexOptTraced(DexoptOptions options) {
9562        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9563        try {
9564            return performDexOptInternal(options);
9565        } finally {
9566            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9567        }
9568    }
9569
9570    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9571    // if the package can now be considered up to date for the given filter.
9572    private int performDexOptInternal(DexoptOptions options) {
9573        PackageParser.Package p;
9574        synchronized (mPackages) {
9575            p = mPackages.get(options.getPackageName());
9576            if (p == null) {
9577                // Package could not be found. Report failure.
9578                return PackageDexOptimizer.DEX_OPT_FAILED;
9579            }
9580            mPackageUsage.maybeWriteAsync(mPackages);
9581            mCompilerStats.maybeWriteAsync();
9582        }
9583        long callingId = Binder.clearCallingIdentity();
9584        try {
9585            synchronized (mInstallLock) {
9586                return performDexOptInternalWithDependenciesLI(p, options);
9587            }
9588        } finally {
9589            Binder.restoreCallingIdentity(callingId);
9590        }
9591    }
9592
9593    public ArraySet<String> getOptimizablePackages() {
9594        ArraySet<String> pkgs = new ArraySet<String>();
9595        synchronized (mPackages) {
9596            for (PackageParser.Package p : mPackages.values()) {
9597                if (PackageDexOptimizer.canOptimizePackage(p)) {
9598                    pkgs.add(p.packageName);
9599                }
9600            }
9601        }
9602        return pkgs;
9603    }
9604
9605    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9606            DexoptOptions options) {
9607        // Select the dex optimizer based on the force parameter.
9608        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9609        //       allocate an object here.
9610        PackageDexOptimizer pdo = options.isForce()
9611                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9612                : mPackageDexOptimizer;
9613
9614        // Dexopt all dependencies first. Note: we ignore the return value and march on
9615        // on errors.
9616        // Note that we are going to call performDexOpt on those libraries as many times as
9617        // they are referenced in packages. When we do a batch of performDexOpt (for example
9618        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9619        // and the first package that uses the library will dexopt it. The
9620        // others will see that the compiled code for the library is up to date.
9621        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9622        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9623        if (!deps.isEmpty()) {
9624            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9625                    options.getCompilerFilter(), options.getSplitName(),
9626                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9627            for (PackageParser.Package depPackage : deps) {
9628                // TODO: Analyze and investigate if we (should) profile libraries.
9629                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9630                        getOrCreateCompilerPackageStats(depPackage),
9631                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9632            }
9633        }
9634        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9635                getOrCreateCompilerPackageStats(p),
9636                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9637    }
9638
9639    /**
9640     * Reconcile the information we have about the secondary dex files belonging to
9641     * {@code packagName} and the actual dex files. For all dex files that were
9642     * deleted, update the internal records and delete the generated oat files.
9643     */
9644    @Override
9645    public void reconcileSecondaryDexFiles(String packageName) {
9646        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9647            return;
9648        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9649            return;
9650        }
9651        mDexManager.reconcileSecondaryDexFiles(packageName);
9652    }
9653
9654    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9655    // a reference there.
9656    /*package*/ DexManager getDexManager() {
9657        return mDexManager;
9658    }
9659
9660    /**
9661     * Execute the background dexopt job immediately.
9662     */
9663    @Override
9664    public boolean runBackgroundDexoptJob() {
9665        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9666            return false;
9667        }
9668        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9669    }
9670
9671    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9672        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9673                || p.usesStaticLibraries != null) {
9674            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9675            Set<String> collectedNames = new HashSet<>();
9676            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9677
9678            retValue.remove(p);
9679
9680            return retValue;
9681        } else {
9682            return Collections.emptyList();
9683        }
9684    }
9685
9686    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9687            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9688        if (!collectedNames.contains(p.packageName)) {
9689            collectedNames.add(p.packageName);
9690            collected.add(p);
9691
9692            if (p.usesLibraries != null) {
9693                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9694                        null, collected, collectedNames);
9695            }
9696            if (p.usesOptionalLibraries != null) {
9697                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9698                        null, collected, collectedNames);
9699            }
9700            if (p.usesStaticLibraries != null) {
9701                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9702                        p.usesStaticLibrariesVersions, collected, collectedNames);
9703            }
9704        }
9705    }
9706
9707    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9708            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9709        final int libNameCount = libs.size();
9710        for (int i = 0; i < libNameCount; i++) {
9711            String libName = libs.get(i);
9712            int version = (versions != null && versions.length == libNameCount)
9713                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9714            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9715            if (libPkg != null) {
9716                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9717            }
9718        }
9719    }
9720
9721    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9722        synchronized (mPackages) {
9723            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9724            if (libEntry != null) {
9725                return mPackages.get(libEntry.apk);
9726            }
9727            return null;
9728        }
9729    }
9730
9731    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9732        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9733        if (versionedLib == null) {
9734            return null;
9735        }
9736        return versionedLib.get(version);
9737    }
9738
9739    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9740        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9741                pkg.staticSharedLibName);
9742        if (versionedLib == null) {
9743            return null;
9744        }
9745        int previousLibVersion = -1;
9746        final int versionCount = versionedLib.size();
9747        for (int i = 0; i < versionCount; i++) {
9748            final int libVersion = versionedLib.keyAt(i);
9749            if (libVersion < pkg.staticSharedLibVersion) {
9750                previousLibVersion = Math.max(previousLibVersion, libVersion);
9751            }
9752        }
9753        if (previousLibVersion >= 0) {
9754            return versionedLib.get(previousLibVersion);
9755        }
9756        return null;
9757    }
9758
9759    public void shutdown() {
9760        mPackageUsage.writeNow(mPackages);
9761        mCompilerStats.writeNow();
9762        mDexManager.writePackageDexUsageNow();
9763    }
9764
9765    @Override
9766    public void dumpProfiles(String packageName) {
9767        PackageParser.Package pkg;
9768        synchronized (mPackages) {
9769            pkg = mPackages.get(packageName);
9770            if (pkg == null) {
9771                throw new IllegalArgumentException("Unknown package: " + packageName);
9772            }
9773        }
9774        /* Only the shell, root, or the app user should be able to dump profiles. */
9775        int callingUid = Binder.getCallingUid();
9776        if (callingUid != Process.SHELL_UID &&
9777            callingUid != Process.ROOT_UID &&
9778            callingUid != pkg.applicationInfo.uid) {
9779            throw new SecurityException("dumpProfiles");
9780        }
9781
9782        synchronized (mInstallLock) {
9783            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9784            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9785            try {
9786                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9787                String codePaths = TextUtils.join(";", allCodePaths);
9788                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9789            } catch (InstallerException e) {
9790                Slog.w(TAG, "Failed to dump profiles", e);
9791            }
9792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9793        }
9794    }
9795
9796    @Override
9797    public void forceDexOpt(String packageName) {
9798        enforceSystemOrRoot("forceDexOpt");
9799
9800        PackageParser.Package pkg;
9801        synchronized (mPackages) {
9802            pkg = mPackages.get(packageName);
9803            if (pkg == null) {
9804                throw new IllegalArgumentException("Unknown package: " + packageName);
9805            }
9806        }
9807
9808        synchronized (mInstallLock) {
9809            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9810
9811            // Whoever is calling forceDexOpt wants a compiled package.
9812            // Don't use profiles since that may cause compilation to be skipped.
9813            final int res = performDexOptInternalWithDependenciesLI(
9814                    pkg,
9815                    new DexoptOptions(packageName,
9816                            getDefaultCompilerFilter(),
9817                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9818
9819            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9820            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9821                throw new IllegalStateException("Failed to dexopt: " + res);
9822            }
9823        }
9824    }
9825
9826    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9827        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9828            Slog.w(TAG, "Unable to update from " + oldPkg.name
9829                    + " to " + newPkg.packageName
9830                    + ": old package not in system partition");
9831            return false;
9832        } else if (mPackages.get(oldPkg.name) != null) {
9833            Slog.w(TAG, "Unable to update from " + oldPkg.name
9834                    + " to " + newPkg.packageName
9835                    + ": old package still exists");
9836            return false;
9837        }
9838        return true;
9839    }
9840
9841    void removeCodePathLI(File codePath) {
9842        if (codePath.isDirectory()) {
9843            try {
9844                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9845            } catch (InstallerException e) {
9846                Slog.w(TAG, "Failed to remove code path", e);
9847            }
9848        } else {
9849            codePath.delete();
9850        }
9851    }
9852
9853    private int[] resolveUserIds(int userId) {
9854        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9855    }
9856
9857    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9858        if (pkg == null) {
9859            Slog.wtf(TAG, "Package was null!", new Throwable());
9860            return;
9861        }
9862        clearAppDataLeafLIF(pkg, userId, flags);
9863        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9864        for (int i = 0; i < childCount; i++) {
9865            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9866        }
9867    }
9868
9869    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9870        final PackageSetting ps;
9871        synchronized (mPackages) {
9872            ps = mSettings.mPackages.get(pkg.packageName);
9873        }
9874        for (int realUserId : resolveUserIds(userId)) {
9875            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9876            try {
9877                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9878                        ceDataInode);
9879            } catch (InstallerException e) {
9880                Slog.w(TAG, String.valueOf(e));
9881            }
9882        }
9883    }
9884
9885    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9886        if (pkg == null) {
9887            Slog.wtf(TAG, "Package was null!", new Throwable());
9888            return;
9889        }
9890        destroyAppDataLeafLIF(pkg, userId, flags);
9891        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9892        for (int i = 0; i < childCount; i++) {
9893            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9894        }
9895    }
9896
9897    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9898        final PackageSetting ps;
9899        synchronized (mPackages) {
9900            ps = mSettings.mPackages.get(pkg.packageName);
9901        }
9902        for (int realUserId : resolveUserIds(userId)) {
9903            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9904            try {
9905                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9906                        ceDataInode);
9907            } catch (InstallerException e) {
9908                Slog.w(TAG, String.valueOf(e));
9909            }
9910            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9911        }
9912    }
9913
9914    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9915        if (pkg == null) {
9916            Slog.wtf(TAG, "Package was null!", new Throwable());
9917            return;
9918        }
9919        destroyAppProfilesLeafLIF(pkg);
9920        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9921        for (int i = 0; i < childCount; i++) {
9922            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9923        }
9924    }
9925
9926    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9927        try {
9928            mInstaller.destroyAppProfiles(pkg.packageName);
9929        } catch (InstallerException e) {
9930            Slog.w(TAG, String.valueOf(e));
9931        }
9932    }
9933
9934    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9935        if (pkg == null) {
9936            Slog.wtf(TAG, "Package was null!", new Throwable());
9937            return;
9938        }
9939        clearAppProfilesLeafLIF(pkg);
9940        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9941        for (int i = 0; i < childCount; i++) {
9942            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9943        }
9944    }
9945
9946    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9947        try {
9948            mInstaller.clearAppProfiles(pkg.packageName);
9949        } catch (InstallerException e) {
9950            Slog.w(TAG, String.valueOf(e));
9951        }
9952    }
9953
9954    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9955            long lastUpdateTime) {
9956        // Set parent install/update time
9957        PackageSetting ps = (PackageSetting) pkg.mExtras;
9958        if (ps != null) {
9959            ps.firstInstallTime = firstInstallTime;
9960            ps.lastUpdateTime = lastUpdateTime;
9961        }
9962        // Set children install/update time
9963        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9964        for (int i = 0; i < childCount; i++) {
9965            PackageParser.Package childPkg = pkg.childPackages.get(i);
9966            ps = (PackageSetting) childPkg.mExtras;
9967            if (ps != null) {
9968                ps.firstInstallTime = firstInstallTime;
9969                ps.lastUpdateTime = lastUpdateTime;
9970            }
9971        }
9972    }
9973
9974    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9975            SharedLibraryEntry file,
9976            PackageParser.Package changingLib) {
9977        if (file.path != null) {
9978            usesLibraryFiles.add(file.path);
9979            return;
9980        }
9981        PackageParser.Package p = mPackages.get(file.apk);
9982        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9983            // If we are doing this while in the middle of updating a library apk,
9984            // then we need to make sure to use that new apk for determining the
9985            // dependencies here.  (We haven't yet finished committing the new apk
9986            // to the package manager state.)
9987            if (p == null || p.packageName.equals(changingLib.packageName)) {
9988                p = changingLib;
9989            }
9990        }
9991        if (p != null) {
9992            usesLibraryFiles.addAll(p.getAllCodePaths());
9993            if (p.usesLibraryFiles != null) {
9994                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9995            }
9996        }
9997    }
9998
9999    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10000            PackageParser.Package changingLib) throws PackageManagerException {
10001        if (pkg == null) {
10002            return;
10003        }
10004        // The collection used here must maintain the order of addition (so
10005        // that libraries are searched in the correct order) and must have no
10006        // duplicates.
10007        Set<String> usesLibraryFiles = null;
10008        if (pkg.usesLibraries != null) {
10009            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10010                    null, null, pkg.packageName, changingLib, true, null);
10011        }
10012        if (pkg.usesStaticLibraries != null) {
10013            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10014                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10015                    pkg.packageName, changingLib, true, usesLibraryFiles);
10016        }
10017        if (pkg.usesOptionalLibraries != null) {
10018            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10019                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10020        }
10021        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10022            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10023        } else {
10024            pkg.usesLibraryFiles = null;
10025        }
10026    }
10027
10028    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10029            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10030            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10031            boolean required, @Nullable Set<String> outUsedLibraries)
10032            throws PackageManagerException {
10033        final int libCount = requestedLibraries.size();
10034        for (int i = 0; i < libCount; i++) {
10035            final String libName = requestedLibraries.get(i);
10036            final int libVersion = requiredVersions != null ? requiredVersions[i]
10037                    : SharedLibraryInfo.VERSION_UNDEFINED;
10038            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10039            if (libEntry == null) {
10040                if (required) {
10041                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10042                            "Package " + packageName + " requires unavailable shared library "
10043                                    + libName + "; failing!");
10044                } else if (DEBUG_SHARED_LIBRARIES) {
10045                    Slog.i(TAG, "Package " + packageName
10046                            + " desires unavailable shared library "
10047                            + libName + "; ignoring!");
10048                }
10049            } else {
10050                if (requiredVersions != null && requiredCertDigests != null) {
10051                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10052                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10053                            "Package " + packageName + " requires unavailable static shared"
10054                                    + " library " + libName + " version "
10055                                    + libEntry.info.getVersion() + "; failing!");
10056                    }
10057
10058                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10059                    if (libPkg == null) {
10060                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10061                                "Package " + packageName + " requires unavailable static shared"
10062                                        + " library; failing!");
10063                    }
10064
10065                    String expectedCertDigest = requiredCertDigests[i];
10066                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10067                                libPkg.mSignatures[0]);
10068                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10069                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10070                                "Package " + packageName + " requires differently signed" +
10071                                        " static shared library; failing!");
10072                    }
10073                }
10074
10075                if (outUsedLibraries == null) {
10076                    // Use LinkedHashSet to preserve the order of files added to
10077                    // usesLibraryFiles while eliminating duplicates.
10078                    outUsedLibraries = new LinkedHashSet<>();
10079                }
10080                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10081            }
10082        }
10083        return outUsedLibraries;
10084    }
10085
10086    private static boolean hasString(List<String> list, List<String> which) {
10087        if (list == null) {
10088            return false;
10089        }
10090        for (int i=list.size()-1; i>=0; i--) {
10091            for (int j=which.size()-1; j>=0; j--) {
10092                if (which.get(j).equals(list.get(i))) {
10093                    return true;
10094                }
10095            }
10096        }
10097        return false;
10098    }
10099
10100    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10101            PackageParser.Package changingPkg) {
10102        ArrayList<PackageParser.Package> res = null;
10103        for (PackageParser.Package pkg : mPackages.values()) {
10104            if (changingPkg != null
10105                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10106                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10107                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10108                            changingPkg.staticSharedLibName)) {
10109                return null;
10110            }
10111            if (res == null) {
10112                res = new ArrayList<>();
10113            }
10114            res.add(pkg);
10115            try {
10116                updateSharedLibrariesLPr(pkg, changingPkg);
10117            } catch (PackageManagerException e) {
10118                // If a system app update or an app and a required lib missing we
10119                // delete the package and for updated system apps keep the data as
10120                // it is better for the user to reinstall than to be in an limbo
10121                // state. Also libs disappearing under an app should never happen
10122                // - just in case.
10123                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10124                    final int flags = pkg.isUpdatedSystemApp()
10125                            ? PackageManager.DELETE_KEEP_DATA : 0;
10126                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10127                            flags , null, true, null);
10128                }
10129                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10130            }
10131        }
10132        return res;
10133    }
10134
10135    /**
10136     * Derive the value of the {@code cpuAbiOverride} based on the provided
10137     * value and an optional stored value from the package settings.
10138     */
10139    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10140        String cpuAbiOverride = null;
10141
10142        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10143            cpuAbiOverride = null;
10144        } else if (abiOverride != null) {
10145            cpuAbiOverride = abiOverride;
10146        } else if (settings != null) {
10147            cpuAbiOverride = settings.cpuAbiOverrideString;
10148        }
10149
10150        return cpuAbiOverride;
10151    }
10152
10153    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10154            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10155                    throws PackageManagerException {
10156        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10157        // If the package has children and this is the first dive in the function
10158        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10159        // whether all packages (parent and children) would be successfully scanned
10160        // before the actual scan since scanning mutates internal state and we want
10161        // to atomically install the package and its children.
10162        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10163            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10164                scanFlags |= SCAN_CHECK_ONLY;
10165            }
10166        } else {
10167            scanFlags &= ~SCAN_CHECK_ONLY;
10168        }
10169
10170        final PackageParser.Package scannedPkg;
10171        try {
10172            // Scan the parent
10173            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10174            // Scan the children
10175            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10176            for (int i = 0; i < childCount; i++) {
10177                PackageParser.Package childPkg = pkg.childPackages.get(i);
10178                scanPackageLI(childPkg, policyFlags,
10179                        scanFlags, currentTime, user);
10180            }
10181        } finally {
10182            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10183        }
10184
10185        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10186            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10187        }
10188
10189        return scannedPkg;
10190    }
10191
10192    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10193            int scanFlags, long currentTime, @Nullable UserHandle user)
10194                    throws PackageManagerException {
10195        boolean success = false;
10196        try {
10197            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10198                    currentTime, user);
10199            success = true;
10200            return res;
10201        } finally {
10202            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10203                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10204                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10205                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10206                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10207            }
10208        }
10209    }
10210
10211    /**
10212     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10213     */
10214    private static boolean apkHasCode(String fileName) {
10215        StrictJarFile jarFile = null;
10216        try {
10217            jarFile = new StrictJarFile(fileName,
10218                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10219            return jarFile.findEntry("classes.dex") != null;
10220        } catch (IOException ignore) {
10221        } finally {
10222            try {
10223                if (jarFile != null) {
10224                    jarFile.close();
10225                }
10226            } catch (IOException ignore) {}
10227        }
10228        return false;
10229    }
10230
10231    /**
10232     * Enforces code policy for the package. This ensures that if an APK has
10233     * declared hasCode="true" in its manifest that the APK actually contains
10234     * code.
10235     *
10236     * @throws PackageManagerException If bytecode could not be found when it should exist
10237     */
10238    private static void assertCodePolicy(PackageParser.Package pkg)
10239            throws PackageManagerException {
10240        final boolean shouldHaveCode =
10241                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10242        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10243            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10244                    "Package " + pkg.baseCodePath + " code is missing");
10245        }
10246
10247        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10248            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10249                final boolean splitShouldHaveCode =
10250                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10251                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10252                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10253                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10254                }
10255            }
10256        }
10257    }
10258
10259    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10260            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10261                    throws PackageManagerException {
10262        if (DEBUG_PACKAGE_SCANNING) {
10263            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10264                Log.d(TAG, "Scanning package " + pkg.packageName);
10265        }
10266
10267        applyPolicy(pkg, policyFlags);
10268
10269        assertPackageIsValid(pkg, policyFlags, scanFlags);
10270
10271        if (Build.IS_DEBUGGABLE &&
10272                pkg.isPrivilegedApp() &&
10273                SystemProperties.getBoolean("pm.dexopt.priv-apps-oob", false)) {
10274            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10275        }
10276
10277        // Initialize package source and resource directories
10278        final File scanFile = new File(pkg.codePath);
10279        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10280        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10281
10282        SharedUserSetting suid = null;
10283        PackageSetting pkgSetting = null;
10284
10285        // Getting the package setting may have a side-effect, so if we
10286        // are only checking if scan would succeed, stash a copy of the
10287        // old setting to restore at the end.
10288        PackageSetting nonMutatedPs = null;
10289
10290        // We keep references to the derived CPU Abis from settings in oder to reuse
10291        // them in the case where we're not upgrading or booting for the first time.
10292        String primaryCpuAbiFromSettings = null;
10293        String secondaryCpuAbiFromSettings = null;
10294
10295        // writer
10296        synchronized (mPackages) {
10297            if (pkg.mSharedUserId != null) {
10298                // SIDE EFFECTS; may potentially allocate a new shared user
10299                suid = mSettings.getSharedUserLPw(
10300                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10301                if (DEBUG_PACKAGE_SCANNING) {
10302                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10303                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10304                                + "): packages=" + suid.packages);
10305                }
10306            }
10307
10308            // Check if we are renaming from an original package name.
10309            PackageSetting origPackage = null;
10310            String realName = null;
10311            if (pkg.mOriginalPackages != null) {
10312                // This package may need to be renamed to a previously
10313                // installed name.  Let's check on that...
10314                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10315                if (pkg.mOriginalPackages.contains(renamed)) {
10316                    // This package had originally been installed as the
10317                    // original name, and we have already taken care of
10318                    // transitioning to the new one.  Just update the new
10319                    // one to continue using the old name.
10320                    realName = pkg.mRealPackage;
10321                    if (!pkg.packageName.equals(renamed)) {
10322                        // Callers into this function may have already taken
10323                        // care of renaming the package; only do it here if
10324                        // it is not already done.
10325                        pkg.setPackageName(renamed);
10326                    }
10327                } else {
10328                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10329                        if ((origPackage = mSettings.getPackageLPr(
10330                                pkg.mOriginalPackages.get(i))) != null) {
10331                            // We do have the package already installed under its
10332                            // original name...  should we use it?
10333                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10334                                // New package is not compatible with original.
10335                                origPackage = null;
10336                                continue;
10337                            } else if (origPackage.sharedUser != null) {
10338                                // Make sure uid is compatible between packages.
10339                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10340                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10341                                            + " to " + pkg.packageName + ": old uid "
10342                                            + origPackage.sharedUser.name
10343                                            + " differs from " + pkg.mSharedUserId);
10344                                    origPackage = null;
10345                                    continue;
10346                                }
10347                                // TODO: Add case when shared user id is added [b/28144775]
10348                            } else {
10349                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10350                                        + pkg.packageName + " to old name " + origPackage.name);
10351                            }
10352                            break;
10353                        }
10354                    }
10355                }
10356            }
10357
10358            if (mTransferedPackages.contains(pkg.packageName)) {
10359                Slog.w(TAG, "Package " + pkg.packageName
10360                        + " was transferred to another, but its .apk remains");
10361            }
10362
10363            // See comments in nonMutatedPs declaration
10364            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10365                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10366                if (foundPs != null) {
10367                    nonMutatedPs = new PackageSetting(foundPs);
10368                }
10369            }
10370
10371            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10372                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10373                if (foundPs != null) {
10374                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10375                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10376                }
10377            }
10378
10379            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10380            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10381                PackageManagerService.reportSettingsProblem(Log.WARN,
10382                        "Package " + pkg.packageName + " shared user changed from "
10383                                + (pkgSetting.sharedUser != null
10384                                        ? pkgSetting.sharedUser.name : "<nothing>")
10385                                + " to "
10386                                + (suid != null ? suid.name : "<nothing>")
10387                                + "; replacing with new");
10388                pkgSetting = null;
10389            }
10390            final PackageSetting oldPkgSetting =
10391                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10392            final PackageSetting disabledPkgSetting =
10393                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10394
10395            String[] usesStaticLibraries = null;
10396            if (pkg.usesStaticLibraries != null) {
10397                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10398                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10399            }
10400
10401            if (pkgSetting == null) {
10402                final String parentPackageName = (pkg.parentPackage != null)
10403                        ? pkg.parentPackage.packageName : null;
10404                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10405                // REMOVE SharedUserSetting from method; update in a separate call
10406                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10407                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10408                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10409                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10410                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10411                        true /*allowInstall*/, instantApp, parentPackageName,
10412                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10413                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10414                // SIDE EFFECTS; updates system state; move elsewhere
10415                if (origPackage != null) {
10416                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10417                }
10418                mSettings.addUserToSettingLPw(pkgSetting);
10419            } else {
10420                // REMOVE SharedUserSetting from method; update in a separate call.
10421                //
10422                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10423                // secondaryCpuAbi are not known at this point so we always update them
10424                // to null here, only to reset them at a later point.
10425                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10426                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10427                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10428                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10429                        UserManagerService.getInstance(), usesStaticLibraries,
10430                        pkg.usesStaticLibrariesVersions);
10431            }
10432            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10433            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10434
10435            // SIDE EFFECTS; modifies system state; move elsewhere
10436            if (pkgSetting.origPackage != null) {
10437                // If we are first transitioning from an original package,
10438                // fix up the new package's name now.  We need to do this after
10439                // looking up the package under its new name, so getPackageLP
10440                // can take care of fiddling things correctly.
10441                pkg.setPackageName(origPackage.name);
10442
10443                // File a report about this.
10444                String msg = "New package " + pkgSetting.realName
10445                        + " renamed to replace old package " + pkgSetting.name;
10446                reportSettingsProblem(Log.WARN, msg);
10447
10448                // Make a note of it.
10449                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10450                    mTransferedPackages.add(origPackage.name);
10451                }
10452
10453                // No longer need to retain this.
10454                pkgSetting.origPackage = null;
10455            }
10456
10457            // SIDE EFFECTS; modifies system state; move elsewhere
10458            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10459                // Make a note of it.
10460                mTransferedPackages.add(pkg.packageName);
10461            }
10462
10463            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10464                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10465            }
10466
10467            if ((scanFlags & SCAN_BOOTING) == 0
10468                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10469                // Check all shared libraries and map to their actual file path.
10470                // We only do this here for apps not on a system dir, because those
10471                // are the only ones that can fail an install due to this.  We
10472                // will take care of the system apps by updating all of their
10473                // library paths after the scan is done. Also during the initial
10474                // scan don't update any libs as we do this wholesale after all
10475                // apps are scanned to avoid dependency based scanning.
10476                updateSharedLibrariesLPr(pkg, null);
10477            }
10478
10479            if (mFoundPolicyFile) {
10480                SELinuxMMAC.assignSeInfoValue(pkg);
10481            }
10482            pkg.applicationInfo.uid = pkgSetting.appId;
10483            pkg.mExtras = pkgSetting;
10484
10485
10486            // Static shared libs have same package with different versions where
10487            // we internally use a synthetic package name to allow multiple versions
10488            // of the same package, therefore we need to compare signatures against
10489            // the package setting for the latest library version.
10490            PackageSetting signatureCheckPs = pkgSetting;
10491            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10492                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10493                if (libraryEntry != null) {
10494                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10495                }
10496            }
10497
10498            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10499                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10500                    // We just determined the app is signed correctly, so bring
10501                    // over the latest parsed certs.
10502                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10503                } else {
10504                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10505                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10506                                "Package " + pkg.packageName + " upgrade keys do not match the "
10507                                + "previously installed version");
10508                    } else {
10509                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10510                        String msg = "System package " + pkg.packageName
10511                                + " signature changed; retaining data.";
10512                        reportSettingsProblem(Log.WARN, msg);
10513                    }
10514                }
10515            } else {
10516                try {
10517                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10518                    verifySignaturesLP(signatureCheckPs, pkg);
10519                    // We just determined the app is signed correctly, so bring
10520                    // over the latest parsed certs.
10521                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10522                } catch (PackageManagerException e) {
10523                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10524                        throw e;
10525                    }
10526                    // The signature has changed, but this package is in the system
10527                    // image...  let's recover!
10528                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10529                    // However...  if this package is part of a shared user, but it
10530                    // doesn't match the signature of the shared user, let's fail.
10531                    // What this means is that you can't change the signatures
10532                    // associated with an overall shared user, which doesn't seem all
10533                    // that unreasonable.
10534                    if (signatureCheckPs.sharedUser != null) {
10535                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10536                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10537                            throw new PackageManagerException(
10538                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10539                                    "Signature mismatch for shared user: "
10540                                            + pkgSetting.sharedUser);
10541                        }
10542                    }
10543                    // File a report about this.
10544                    String msg = "System package " + pkg.packageName
10545                            + " signature changed; retaining data.";
10546                    reportSettingsProblem(Log.WARN, msg);
10547                }
10548            }
10549
10550            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10551                // This package wants to adopt ownership of permissions from
10552                // another package.
10553                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10554                    final String origName = pkg.mAdoptPermissions.get(i);
10555                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10556                    if (orig != null) {
10557                        if (verifyPackageUpdateLPr(orig, pkg)) {
10558                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10559                                    + pkg.packageName);
10560                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10561                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10562                        }
10563                    }
10564                }
10565            }
10566        }
10567
10568        pkg.applicationInfo.processName = fixProcessName(
10569                pkg.applicationInfo.packageName,
10570                pkg.applicationInfo.processName);
10571
10572        if (pkg != mPlatformPackage) {
10573            // Get all of our default paths setup
10574            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10575        }
10576
10577        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10578
10579        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10580            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10581                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10582                final boolean extractNativeLibs = !pkg.isLibrary();
10583                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10584                        mAppLib32InstallDir);
10585                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10586
10587                // Some system apps still use directory structure for native libraries
10588                // in which case we might end up not detecting abi solely based on apk
10589                // structure. Try to detect abi based on directory structure.
10590                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10591                        pkg.applicationInfo.primaryCpuAbi == null) {
10592                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10593                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10594                }
10595            } else {
10596                // This is not a first boot or an upgrade, don't bother deriving the
10597                // ABI during the scan. Instead, trust the value that was stored in the
10598                // package setting.
10599                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10600                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10601
10602                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10603
10604                if (DEBUG_ABI_SELECTION) {
10605                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10606                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10607                        pkg.applicationInfo.secondaryCpuAbi);
10608                }
10609            }
10610        } else {
10611            if ((scanFlags & SCAN_MOVE) != 0) {
10612                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10613                // but we already have this packages package info in the PackageSetting. We just
10614                // use that and derive the native library path based on the new codepath.
10615                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10616                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10617            }
10618
10619            // Set native library paths again. For moves, the path will be updated based on the
10620            // ABIs we've determined above. For non-moves, the path will be updated based on the
10621            // ABIs we determined during compilation, but the path will depend on the final
10622            // package path (after the rename away from the stage path).
10623            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10624        }
10625
10626        // This is a special case for the "system" package, where the ABI is
10627        // dictated by the zygote configuration (and init.rc). We should keep track
10628        // of this ABI so that we can deal with "normal" applications that run under
10629        // the same UID correctly.
10630        if (mPlatformPackage == pkg) {
10631            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10632                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10633        }
10634
10635        // If there's a mismatch between the abi-override in the package setting
10636        // and the abiOverride specified for the install. Warn about this because we
10637        // would've already compiled the app without taking the package setting into
10638        // account.
10639        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10640            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10641                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10642                        " for package " + pkg.packageName);
10643            }
10644        }
10645
10646        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10647        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10648        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10649
10650        // Copy the derived override back to the parsed package, so that we can
10651        // update the package settings accordingly.
10652        pkg.cpuAbiOverride = cpuAbiOverride;
10653
10654        if (DEBUG_ABI_SELECTION) {
10655            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10656                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10657                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10658        }
10659
10660        // Push the derived path down into PackageSettings so we know what to
10661        // clean up at uninstall time.
10662        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10663
10664        if (DEBUG_ABI_SELECTION) {
10665            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10666                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10667                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10668        }
10669
10670        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10671        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10672            // We don't do this here during boot because we can do it all
10673            // at once after scanning all existing packages.
10674            //
10675            // We also do this *before* we perform dexopt on this package, so that
10676            // we can avoid redundant dexopts, and also to make sure we've got the
10677            // code and package path correct.
10678            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10679        }
10680
10681        if (mFactoryTest && pkg.requestedPermissions.contains(
10682                android.Manifest.permission.FACTORY_TEST)) {
10683            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10684        }
10685
10686        if (isSystemApp(pkg)) {
10687            pkgSetting.isOrphaned = true;
10688        }
10689
10690        // Take care of first install / last update times.
10691        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10692        if (currentTime != 0) {
10693            if (pkgSetting.firstInstallTime == 0) {
10694                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10695            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10696                pkgSetting.lastUpdateTime = currentTime;
10697            }
10698        } else if (pkgSetting.firstInstallTime == 0) {
10699            // We need *something*.  Take time time stamp of the file.
10700            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10701        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10702            if (scanFileTime != pkgSetting.timeStamp) {
10703                // A package on the system image has changed; consider this
10704                // to be an update.
10705                pkgSetting.lastUpdateTime = scanFileTime;
10706            }
10707        }
10708        pkgSetting.setTimeStamp(scanFileTime);
10709
10710        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10711            if (nonMutatedPs != null) {
10712                synchronized (mPackages) {
10713                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10714                }
10715            }
10716        } else {
10717            final int userId = user == null ? 0 : user.getIdentifier();
10718            // Modify state for the given package setting
10719            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10720                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10721            if (pkgSetting.getInstantApp(userId)) {
10722                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10723            }
10724        }
10725        return pkg;
10726    }
10727
10728    /**
10729     * Applies policy to the parsed package based upon the given policy flags.
10730     * Ensures the package is in a good state.
10731     * <p>
10732     * Implementation detail: This method must NOT have any side effect. It would
10733     * ideally be static, but, it requires locks to read system state.
10734     */
10735    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10736        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10737            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10738            if (pkg.applicationInfo.isDirectBootAware()) {
10739                // we're direct boot aware; set for all components
10740                for (PackageParser.Service s : pkg.services) {
10741                    s.info.encryptionAware = s.info.directBootAware = true;
10742                }
10743                for (PackageParser.Provider p : pkg.providers) {
10744                    p.info.encryptionAware = p.info.directBootAware = true;
10745                }
10746                for (PackageParser.Activity a : pkg.activities) {
10747                    a.info.encryptionAware = a.info.directBootAware = true;
10748                }
10749                for (PackageParser.Activity r : pkg.receivers) {
10750                    r.info.encryptionAware = r.info.directBootAware = true;
10751                }
10752            }
10753        } else {
10754            // Only allow system apps to be flagged as core apps.
10755            pkg.coreApp = false;
10756            // clear flags not applicable to regular apps
10757            pkg.applicationInfo.privateFlags &=
10758                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10759            pkg.applicationInfo.privateFlags &=
10760                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10761        }
10762        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10763
10764        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10765            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10766        }
10767
10768        if (!isSystemApp(pkg)) {
10769            // Only system apps can use these features.
10770            pkg.mOriginalPackages = null;
10771            pkg.mRealPackage = null;
10772            pkg.mAdoptPermissions = null;
10773        }
10774    }
10775
10776    /**
10777     * Asserts the parsed package is valid according to the given policy. If the
10778     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10779     * <p>
10780     * Implementation detail: This method must NOT have any side effects. It would
10781     * ideally be static, but, it requires locks to read system state.
10782     *
10783     * @throws PackageManagerException If the package fails any of the validation checks
10784     */
10785    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10786            throws PackageManagerException {
10787        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10788            assertCodePolicy(pkg);
10789        }
10790
10791        if (pkg.applicationInfo.getCodePath() == null ||
10792                pkg.applicationInfo.getResourcePath() == null) {
10793            // Bail out. The resource and code paths haven't been set.
10794            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10795                    "Code and resource paths haven't been set correctly");
10796        }
10797
10798        // Make sure we're not adding any bogus keyset info
10799        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10800        ksms.assertScannedPackageValid(pkg);
10801
10802        synchronized (mPackages) {
10803            // The special "android" package can only be defined once
10804            if (pkg.packageName.equals("android")) {
10805                if (mAndroidApplication != null) {
10806                    Slog.w(TAG, "*************************************************");
10807                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10808                    Slog.w(TAG, " codePath=" + pkg.codePath);
10809                    Slog.w(TAG, "*************************************************");
10810                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10811                            "Core android package being redefined.  Skipping.");
10812                }
10813            }
10814
10815            // A package name must be unique; don't allow duplicates
10816            if (mPackages.containsKey(pkg.packageName)) {
10817                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10818                        "Application package " + pkg.packageName
10819                        + " already installed.  Skipping duplicate.");
10820            }
10821
10822            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10823                // Static libs have a synthetic package name containing the version
10824                // but we still want the base name to be unique.
10825                if (mPackages.containsKey(pkg.manifestPackageName)) {
10826                    throw new PackageManagerException(
10827                            "Duplicate static shared lib provider package");
10828                }
10829
10830                // Static shared libraries should have at least O target SDK
10831                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10832                    throw new PackageManagerException(
10833                            "Packages declaring static-shared libs must target O SDK or higher");
10834                }
10835
10836                // Package declaring static a shared lib cannot be instant apps
10837                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10838                    throw new PackageManagerException(
10839                            "Packages declaring static-shared libs cannot be instant apps");
10840                }
10841
10842                // Package declaring static a shared lib cannot be renamed since the package
10843                // name is synthetic and apps can't code around package manager internals.
10844                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10845                    throw new PackageManagerException(
10846                            "Packages declaring static-shared libs cannot be renamed");
10847                }
10848
10849                // Package declaring static a shared lib cannot declare child packages
10850                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10851                    throw new PackageManagerException(
10852                            "Packages declaring static-shared libs cannot have child packages");
10853                }
10854
10855                // Package declaring static a shared lib cannot declare dynamic libs
10856                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10857                    throw new PackageManagerException(
10858                            "Packages declaring static-shared libs cannot declare dynamic libs");
10859                }
10860
10861                // Package declaring static a shared lib cannot declare shared users
10862                if (pkg.mSharedUserId != null) {
10863                    throw new PackageManagerException(
10864                            "Packages declaring static-shared libs cannot declare shared users");
10865                }
10866
10867                // Static shared libs cannot declare activities
10868                if (!pkg.activities.isEmpty()) {
10869                    throw new PackageManagerException(
10870                            "Static shared libs cannot declare activities");
10871                }
10872
10873                // Static shared libs cannot declare services
10874                if (!pkg.services.isEmpty()) {
10875                    throw new PackageManagerException(
10876                            "Static shared libs cannot declare services");
10877                }
10878
10879                // Static shared libs cannot declare providers
10880                if (!pkg.providers.isEmpty()) {
10881                    throw new PackageManagerException(
10882                            "Static shared libs cannot declare content providers");
10883                }
10884
10885                // Static shared libs cannot declare receivers
10886                if (!pkg.receivers.isEmpty()) {
10887                    throw new PackageManagerException(
10888                            "Static shared libs cannot declare broadcast receivers");
10889                }
10890
10891                // Static shared libs cannot declare permission groups
10892                if (!pkg.permissionGroups.isEmpty()) {
10893                    throw new PackageManagerException(
10894                            "Static shared libs cannot declare permission groups");
10895                }
10896
10897                // Static shared libs cannot declare permissions
10898                if (!pkg.permissions.isEmpty()) {
10899                    throw new PackageManagerException(
10900                            "Static shared libs cannot declare permissions");
10901                }
10902
10903                // Static shared libs cannot declare protected broadcasts
10904                if (pkg.protectedBroadcasts != null) {
10905                    throw new PackageManagerException(
10906                            "Static shared libs cannot declare protected broadcasts");
10907                }
10908
10909                // Static shared libs cannot be overlay targets
10910                if (pkg.mOverlayTarget != null) {
10911                    throw new PackageManagerException(
10912                            "Static shared libs cannot be overlay targets");
10913                }
10914
10915                // The version codes must be ordered as lib versions
10916                int minVersionCode = Integer.MIN_VALUE;
10917                int maxVersionCode = Integer.MAX_VALUE;
10918
10919                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10920                        pkg.staticSharedLibName);
10921                if (versionedLib != null) {
10922                    final int versionCount = versionedLib.size();
10923                    for (int i = 0; i < versionCount; i++) {
10924                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10925                        final int libVersionCode = libInfo.getDeclaringPackage()
10926                                .getVersionCode();
10927                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10928                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10929                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10930                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10931                        } else {
10932                            minVersionCode = maxVersionCode = libVersionCode;
10933                            break;
10934                        }
10935                    }
10936                }
10937                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10938                    throw new PackageManagerException("Static shared"
10939                            + " lib version codes must be ordered as lib versions");
10940                }
10941            }
10942
10943            // Only privileged apps and updated privileged apps can add child packages.
10944            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10945                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10946                    throw new PackageManagerException("Only privileged apps can add child "
10947                            + "packages. Ignoring package " + pkg.packageName);
10948                }
10949                final int childCount = pkg.childPackages.size();
10950                for (int i = 0; i < childCount; i++) {
10951                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10952                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10953                            childPkg.packageName)) {
10954                        throw new PackageManagerException("Can't override child of "
10955                                + "another disabled app. Ignoring package " + pkg.packageName);
10956                    }
10957                }
10958            }
10959
10960            // If we're only installing presumed-existing packages, require that the
10961            // scanned APK is both already known and at the path previously established
10962            // for it.  Previously unknown packages we pick up normally, but if we have an
10963            // a priori expectation about this package's install presence, enforce it.
10964            // With a singular exception for new system packages. When an OTA contains
10965            // a new system package, we allow the codepath to change from a system location
10966            // to the user-installed location. If we don't allow this change, any newer,
10967            // user-installed version of the application will be ignored.
10968            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10969                if (mExpectingBetter.containsKey(pkg.packageName)) {
10970                    logCriticalInfo(Log.WARN,
10971                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10972                } else {
10973                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10974                    if (known != null) {
10975                        if (DEBUG_PACKAGE_SCANNING) {
10976                            Log.d(TAG, "Examining " + pkg.codePath
10977                                    + " and requiring known paths " + known.codePathString
10978                                    + " & " + known.resourcePathString);
10979                        }
10980                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10981                                || !pkg.applicationInfo.getResourcePath().equals(
10982                                        known.resourcePathString)) {
10983                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10984                                    "Application package " + pkg.packageName
10985                                    + " found at " + pkg.applicationInfo.getCodePath()
10986                                    + " but expected at " + known.codePathString
10987                                    + "; ignoring.");
10988                        }
10989                    }
10990                }
10991            }
10992
10993            // Verify that this new package doesn't have any content providers
10994            // that conflict with existing packages.  Only do this if the
10995            // package isn't already installed, since we don't want to break
10996            // things that are installed.
10997            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10998                final int N = pkg.providers.size();
10999                int i;
11000                for (i=0; i<N; i++) {
11001                    PackageParser.Provider p = pkg.providers.get(i);
11002                    if (p.info.authority != null) {
11003                        String names[] = p.info.authority.split(";");
11004                        for (int j = 0; j < names.length; j++) {
11005                            if (mProvidersByAuthority.containsKey(names[j])) {
11006                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11007                                final String otherPackageName =
11008                                        ((other != null && other.getComponentName() != null) ?
11009                                                other.getComponentName().getPackageName() : "?");
11010                                throw new PackageManagerException(
11011                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11012                                        "Can't install because provider name " + names[j]
11013                                                + " (in package " + pkg.applicationInfo.packageName
11014                                                + ") is already used by " + otherPackageName);
11015                            }
11016                        }
11017                    }
11018                }
11019            }
11020        }
11021    }
11022
11023    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11024            int type, String declaringPackageName, int declaringVersionCode) {
11025        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11026        if (versionedLib == null) {
11027            versionedLib = new SparseArray<>();
11028            mSharedLibraries.put(name, versionedLib);
11029            if (type == SharedLibraryInfo.TYPE_STATIC) {
11030                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11031            }
11032        } else if (versionedLib.indexOfKey(version) >= 0) {
11033            return false;
11034        }
11035        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11036                version, type, declaringPackageName, declaringVersionCode);
11037        versionedLib.put(version, libEntry);
11038        return true;
11039    }
11040
11041    private boolean removeSharedLibraryLPw(String name, int version) {
11042        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11043        if (versionedLib == null) {
11044            return false;
11045        }
11046        final int libIdx = versionedLib.indexOfKey(version);
11047        if (libIdx < 0) {
11048            return false;
11049        }
11050        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11051        versionedLib.remove(version);
11052        if (versionedLib.size() <= 0) {
11053            mSharedLibraries.remove(name);
11054            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11055                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11056                        .getPackageName());
11057            }
11058        }
11059        return true;
11060    }
11061
11062    /**
11063     * Adds a scanned package to the system. When this method is finished, the package will
11064     * be available for query, resolution, etc...
11065     */
11066    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11067            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11068        final String pkgName = pkg.packageName;
11069        if (mCustomResolverComponentName != null &&
11070                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11071            setUpCustomResolverActivity(pkg);
11072        }
11073
11074        if (pkg.packageName.equals("android")) {
11075            synchronized (mPackages) {
11076                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11077                    // Set up information for our fall-back user intent resolution activity.
11078                    mPlatformPackage = pkg;
11079                    pkg.mVersionCode = mSdkVersion;
11080                    mAndroidApplication = pkg.applicationInfo;
11081                    if (!mResolverReplaced) {
11082                        mResolveActivity.applicationInfo = mAndroidApplication;
11083                        mResolveActivity.name = ResolverActivity.class.getName();
11084                        mResolveActivity.packageName = mAndroidApplication.packageName;
11085                        mResolveActivity.processName = "system:ui";
11086                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11087                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11088                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11089                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11090                        mResolveActivity.exported = true;
11091                        mResolveActivity.enabled = true;
11092                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11093                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11094                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11095                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11096                                | ActivityInfo.CONFIG_ORIENTATION
11097                                | ActivityInfo.CONFIG_KEYBOARD
11098                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11099                        mResolveInfo.activityInfo = mResolveActivity;
11100                        mResolveInfo.priority = 0;
11101                        mResolveInfo.preferredOrder = 0;
11102                        mResolveInfo.match = 0;
11103                        mResolveComponentName = new ComponentName(
11104                                mAndroidApplication.packageName, mResolveActivity.name);
11105                    }
11106                }
11107            }
11108        }
11109
11110        ArrayList<PackageParser.Package> clientLibPkgs = null;
11111        // writer
11112        synchronized (mPackages) {
11113            boolean hasStaticSharedLibs = false;
11114
11115            // Any app can add new static shared libraries
11116            if (pkg.staticSharedLibName != null) {
11117                // Static shared libs don't allow renaming as they have synthetic package
11118                // names to allow install of multiple versions, so use name from manifest.
11119                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11120                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11121                        pkg.manifestPackageName, pkg.mVersionCode)) {
11122                    hasStaticSharedLibs = true;
11123                } else {
11124                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11125                                + pkg.staticSharedLibName + " already exists; skipping");
11126                }
11127                // Static shared libs cannot be updated once installed since they
11128                // use synthetic package name which includes the version code, so
11129                // not need to update other packages's shared lib dependencies.
11130            }
11131
11132            if (!hasStaticSharedLibs
11133                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11134                // Only system apps can add new dynamic shared libraries.
11135                if (pkg.libraryNames != null) {
11136                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11137                        String name = pkg.libraryNames.get(i);
11138                        boolean allowed = false;
11139                        if (pkg.isUpdatedSystemApp()) {
11140                            // New library entries can only be added through the
11141                            // system image.  This is important to get rid of a lot
11142                            // of nasty edge cases: for example if we allowed a non-
11143                            // system update of the app to add a library, then uninstalling
11144                            // the update would make the library go away, and assumptions
11145                            // we made such as through app install filtering would now
11146                            // have allowed apps on the device which aren't compatible
11147                            // with it.  Better to just have the restriction here, be
11148                            // conservative, and create many fewer cases that can negatively
11149                            // impact the user experience.
11150                            final PackageSetting sysPs = mSettings
11151                                    .getDisabledSystemPkgLPr(pkg.packageName);
11152                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11153                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11154                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11155                                        allowed = true;
11156                                        break;
11157                                    }
11158                                }
11159                            }
11160                        } else {
11161                            allowed = true;
11162                        }
11163                        if (allowed) {
11164                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11165                                    SharedLibraryInfo.VERSION_UNDEFINED,
11166                                    SharedLibraryInfo.TYPE_DYNAMIC,
11167                                    pkg.packageName, pkg.mVersionCode)) {
11168                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11169                                        + name + " already exists; skipping");
11170                            }
11171                        } else {
11172                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11173                                    + name + " that is not declared on system image; skipping");
11174                        }
11175                    }
11176
11177                    if ((scanFlags & SCAN_BOOTING) == 0) {
11178                        // If we are not booting, we need to update any applications
11179                        // that are clients of our shared library.  If we are booting,
11180                        // this will all be done once the scan is complete.
11181                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11182                    }
11183                }
11184            }
11185        }
11186
11187        if ((scanFlags & SCAN_BOOTING) != 0) {
11188            // No apps can run during boot scan, so they don't need to be frozen
11189        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11190            // Caller asked to not kill app, so it's probably not frozen
11191        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11192            // Caller asked us to ignore frozen check for some reason; they
11193            // probably didn't know the package name
11194        } else {
11195            // We're doing major surgery on this package, so it better be frozen
11196            // right now to keep it from launching
11197            checkPackageFrozen(pkgName);
11198        }
11199
11200        // Also need to kill any apps that are dependent on the library.
11201        if (clientLibPkgs != null) {
11202            for (int i=0; i<clientLibPkgs.size(); i++) {
11203                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11204                killApplication(clientPkg.applicationInfo.packageName,
11205                        clientPkg.applicationInfo.uid, "update lib");
11206            }
11207        }
11208
11209        // writer
11210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11211
11212        synchronized (mPackages) {
11213            // We don't expect installation to fail beyond this point
11214
11215            // Add the new setting to mSettings
11216            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11217            // Add the new setting to mPackages
11218            mPackages.put(pkg.applicationInfo.packageName, pkg);
11219            // Make sure we don't accidentally delete its data.
11220            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11221            while (iter.hasNext()) {
11222                PackageCleanItem item = iter.next();
11223                if (pkgName.equals(item.packageName)) {
11224                    iter.remove();
11225                }
11226            }
11227
11228            // Add the package's KeySets to the global KeySetManagerService
11229            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11230            ksms.addScannedPackageLPw(pkg);
11231
11232            int N = pkg.providers.size();
11233            StringBuilder r = null;
11234            int i;
11235            for (i=0; i<N; i++) {
11236                PackageParser.Provider p = pkg.providers.get(i);
11237                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11238                        p.info.processName);
11239                mProviders.addProvider(p);
11240                p.syncable = p.info.isSyncable;
11241                if (p.info.authority != null) {
11242                    String names[] = p.info.authority.split(";");
11243                    p.info.authority = null;
11244                    for (int j = 0; j < names.length; j++) {
11245                        if (j == 1 && p.syncable) {
11246                            // We only want the first authority for a provider to possibly be
11247                            // syncable, so if we already added this provider using a different
11248                            // authority clear the syncable flag. We copy the provider before
11249                            // changing it because the mProviders object contains a reference
11250                            // to a provider that we don't want to change.
11251                            // Only do this for the second authority since the resulting provider
11252                            // object can be the same for all future authorities for this provider.
11253                            p = new PackageParser.Provider(p);
11254                            p.syncable = false;
11255                        }
11256                        if (!mProvidersByAuthority.containsKey(names[j])) {
11257                            mProvidersByAuthority.put(names[j], p);
11258                            if (p.info.authority == null) {
11259                                p.info.authority = names[j];
11260                            } else {
11261                                p.info.authority = p.info.authority + ";" + names[j];
11262                            }
11263                            if (DEBUG_PACKAGE_SCANNING) {
11264                                if (chatty)
11265                                    Log.d(TAG, "Registered content provider: " + names[j]
11266                                            + ", className = " + p.info.name + ", isSyncable = "
11267                                            + p.info.isSyncable);
11268                            }
11269                        } else {
11270                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11271                            Slog.w(TAG, "Skipping provider name " + names[j] +
11272                                    " (in package " + pkg.applicationInfo.packageName +
11273                                    "): name already used by "
11274                                    + ((other != null && other.getComponentName() != null)
11275                                            ? other.getComponentName().getPackageName() : "?"));
11276                        }
11277                    }
11278                }
11279                if (chatty) {
11280                    if (r == null) {
11281                        r = new StringBuilder(256);
11282                    } else {
11283                        r.append(' ');
11284                    }
11285                    r.append(p.info.name);
11286                }
11287            }
11288            if (r != null) {
11289                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11290            }
11291
11292            N = pkg.services.size();
11293            r = null;
11294            for (i=0; i<N; i++) {
11295                PackageParser.Service s = pkg.services.get(i);
11296                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11297                        s.info.processName);
11298                mServices.addService(s);
11299                if (chatty) {
11300                    if (r == null) {
11301                        r = new StringBuilder(256);
11302                    } else {
11303                        r.append(' ');
11304                    }
11305                    r.append(s.info.name);
11306                }
11307            }
11308            if (r != null) {
11309                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11310            }
11311
11312            N = pkg.receivers.size();
11313            r = null;
11314            for (i=0; i<N; i++) {
11315                PackageParser.Activity a = pkg.receivers.get(i);
11316                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11317                        a.info.processName);
11318                mReceivers.addActivity(a, "receiver");
11319                if (chatty) {
11320                    if (r == null) {
11321                        r = new StringBuilder(256);
11322                    } else {
11323                        r.append(' ');
11324                    }
11325                    r.append(a.info.name);
11326                }
11327            }
11328            if (r != null) {
11329                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11330            }
11331
11332            N = pkg.activities.size();
11333            r = null;
11334            for (i=0; i<N; i++) {
11335                PackageParser.Activity a = pkg.activities.get(i);
11336                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11337                        a.info.processName);
11338                mActivities.addActivity(a, "activity");
11339                if (chatty) {
11340                    if (r == null) {
11341                        r = new StringBuilder(256);
11342                    } else {
11343                        r.append(' ');
11344                    }
11345                    r.append(a.info.name);
11346                }
11347            }
11348            if (r != null) {
11349                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11350            }
11351
11352            N = pkg.permissionGroups.size();
11353            r = null;
11354            for (i=0; i<N; i++) {
11355                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11356                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11357                final String curPackageName = cur == null ? null : cur.info.packageName;
11358                // Dont allow ephemeral apps to define new permission groups.
11359                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11360                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11361                            + pg.info.packageName
11362                            + " ignored: instant apps cannot define new permission groups.");
11363                    continue;
11364                }
11365                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11366                if (cur == null || isPackageUpdate) {
11367                    mPermissionGroups.put(pg.info.name, pg);
11368                    if (chatty) {
11369                        if (r == null) {
11370                            r = new StringBuilder(256);
11371                        } else {
11372                            r.append(' ');
11373                        }
11374                        if (isPackageUpdate) {
11375                            r.append("UPD:");
11376                        }
11377                        r.append(pg.info.name);
11378                    }
11379                } else {
11380                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11381                            + pg.info.packageName + " ignored: original from "
11382                            + cur.info.packageName);
11383                    if (chatty) {
11384                        if (r == null) {
11385                            r = new StringBuilder(256);
11386                        } else {
11387                            r.append(' ');
11388                        }
11389                        r.append("DUP:");
11390                        r.append(pg.info.name);
11391                    }
11392                }
11393            }
11394            if (r != null) {
11395                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11396            }
11397
11398            N = pkg.permissions.size();
11399            r = null;
11400            for (i=0; i<N; i++) {
11401                PackageParser.Permission p = pkg.permissions.get(i);
11402
11403                // Dont allow ephemeral apps to define new permissions.
11404                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11405                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11406                            + p.info.packageName
11407                            + " ignored: instant apps cannot define new permissions.");
11408                    continue;
11409                }
11410
11411                // Assume by default that we did not install this permission into the system.
11412                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11413
11414                // Now that permission groups have a special meaning, we ignore permission
11415                // groups for legacy apps to prevent unexpected behavior. In particular,
11416                // permissions for one app being granted to someone just because they happen
11417                // to be in a group defined by another app (before this had no implications).
11418                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11419                    p.group = mPermissionGroups.get(p.info.group);
11420                    // Warn for a permission in an unknown group.
11421                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11422                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11423                                + p.info.packageName + " in an unknown group " + p.info.group);
11424                    }
11425                }
11426
11427                ArrayMap<String, BasePermission> permissionMap =
11428                        p.tree ? mSettings.mPermissionTrees
11429                                : mSettings.mPermissions;
11430                BasePermission bp = permissionMap.get(p.info.name);
11431
11432                // Allow system apps to redefine non-system permissions
11433                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11434                    final boolean currentOwnerIsSystem = (bp.perm != null
11435                            && isSystemApp(bp.perm.owner));
11436                    if (isSystemApp(p.owner)) {
11437                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11438                            // It's a built-in permission and no owner, take ownership now
11439                            bp.packageSetting = pkgSetting;
11440                            bp.perm = p;
11441                            bp.uid = pkg.applicationInfo.uid;
11442                            bp.sourcePackage = p.info.packageName;
11443                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11444                        } else if (!currentOwnerIsSystem) {
11445                            String msg = "New decl " + p.owner + " of permission  "
11446                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11447                            reportSettingsProblem(Log.WARN, msg);
11448                            bp = null;
11449                        }
11450                    }
11451                }
11452
11453                if (bp == null) {
11454                    bp = new BasePermission(p.info.name, p.info.packageName,
11455                            BasePermission.TYPE_NORMAL);
11456                    permissionMap.put(p.info.name, bp);
11457                }
11458
11459                if (bp.perm == null) {
11460                    if (bp.sourcePackage == null
11461                            || bp.sourcePackage.equals(p.info.packageName)) {
11462                        BasePermission tree = findPermissionTreeLP(p.info.name);
11463                        if (tree == null
11464                                || tree.sourcePackage.equals(p.info.packageName)) {
11465                            bp.packageSetting = pkgSetting;
11466                            bp.perm = p;
11467                            bp.uid = pkg.applicationInfo.uid;
11468                            bp.sourcePackage = p.info.packageName;
11469                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11470                            if (chatty) {
11471                                if (r == null) {
11472                                    r = new StringBuilder(256);
11473                                } else {
11474                                    r.append(' ');
11475                                }
11476                                r.append(p.info.name);
11477                            }
11478                        } else {
11479                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11480                                    + p.info.packageName + " ignored: base tree "
11481                                    + tree.name + " is from package "
11482                                    + tree.sourcePackage);
11483                        }
11484                    } else {
11485                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11486                                + p.info.packageName + " ignored: original from "
11487                                + bp.sourcePackage);
11488                    }
11489                } else if (chatty) {
11490                    if (r == null) {
11491                        r = new StringBuilder(256);
11492                    } else {
11493                        r.append(' ');
11494                    }
11495                    r.append("DUP:");
11496                    r.append(p.info.name);
11497                }
11498                if (bp.perm == p) {
11499                    bp.protectionLevel = p.info.protectionLevel;
11500                }
11501            }
11502
11503            if (r != null) {
11504                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11505            }
11506
11507            N = pkg.instrumentation.size();
11508            r = null;
11509            for (i=0; i<N; i++) {
11510                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11511                a.info.packageName = pkg.applicationInfo.packageName;
11512                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11513                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11514                a.info.splitNames = pkg.splitNames;
11515                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11516                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11517                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11518                a.info.dataDir = pkg.applicationInfo.dataDir;
11519                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11520                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11521                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11522                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11523                mInstrumentation.put(a.getComponentName(), a);
11524                if (chatty) {
11525                    if (r == null) {
11526                        r = new StringBuilder(256);
11527                    } else {
11528                        r.append(' ');
11529                    }
11530                    r.append(a.info.name);
11531                }
11532            }
11533            if (r != null) {
11534                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11535            }
11536
11537            if (pkg.protectedBroadcasts != null) {
11538                N = pkg.protectedBroadcasts.size();
11539                for (i=0; i<N; i++) {
11540                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11541                }
11542            }
11543        }
11544
11545        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11546    }
11547
11548    /**
11549     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11550     * is derived purely on the basis of the contents of {@code scanFile} and
11551     * {@code cpuAbiOverride}.
11552     *
11553     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11554     */
11555    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11556                                 String cpuAbiOverride, boolean extractLibs,
11557                                 File appLib32InstallDir)
11558            throws PackageManagerException {
11559        // Give ourselves some initial paths; we'll come back for another
11560        // pass once we've determined ABI below.
11561        setNativeLibraryPaths(pkg, appLib32InstallDir);
11562
11563        // We would never need to extract libs for forward-locked and external packages,
11564        // since the container service will do it for us. We shouldn't attempt to
11565        // extract libs from system app when it was not updated.
11566        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11567                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11568            extractLibs = false;
11569        }
11570
11571        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11572        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11573
11574        NativeLibraryHelper.Handle handle = null;
11575        try {
11576            handle = NativeLibraryHelper.Handle.create(pkg);
11577            // TODO(multiArch): This can be null for apps that didn't go through the
11578            // usual installation process. We can calculate it again, like we
11579            // do during install time.
11580            //
11581            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11582            // unnecessary.
11583            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11584
11585            // Null out the abis so that they can be recalculated.
11586            pkg.applicationInfo.primaryCpuAbi = null;
11587            pkg.applicationInfo.secondaryCpuAbi = null;
11588            if (isMultiArch(pkg.applicationInfo)) {
11589                // Warn if we've set an abiOverride for multi-lib packages..
11590                // By definition, we need to copy both 32 and 64 bit libraries for
11591                // such packages.
11592                if (pkg.cpuAbiOverride != null
11593                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11594                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11595                }
11596
11597                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11598                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11599                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11600                    if (extractLibs) {
11601                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11602                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11603                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11604                                useIsaSpecificSubdirs);
11605                    } else {
11606                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11607                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11608                    }
11609                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11610                }
11611
11612                // Shared library native code should be in the APK zip aligned
11613                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11614                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11615                            "Shared library native lib extraction not supported");
11616                }
11617
11618                maybeThrowExceptionForMultiArchCopy(
11619                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11620
11621                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11622                    if (extractLibs) {
11623                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11624                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11625                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11626                                useIsaSpecificSubdirs);
11627                    } else {
11628                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11629                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11630                    }
11631                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11632                }
11633
11634                maybeThrowExceptionForMultiArchCopy(
11635                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11636
11637                if (abi64 >= 0) {
11638                    // Shared library native libs should be in the APK zip aligned
11639                    if (extractLibs && pkg.isLibrary()) {
11640                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11641                                "Shared library native lib extraction not supported");
11642                    }
11643                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11644                }
11645
11646                if (abi32 >= 0) {
11647                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11648                    if (abi64 >= 0) {
11649                        if (pkg.use32bitAbi) {
11650                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11651                            pkg.applicationInfo.primaryCpuAbi = abi;
11652                        } else {
11653                            pkg.applicationInfo.secondaryCpuAbi = abi;
11654                        }
11655                    } else {
11656                        pkg.applicationInfo.primaryCpuAbi = abi;
11657                    }
11658                }
11659            } else {
11660                String[] abiList = (cpuAbiOverride != null) ?
11661                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11662
11663                // Enable gross and lame hacks for apps that are built with old
11664                // SDK tools. We must scan their APKs for renderscript bitcode and
11665                // not launch them if it's present. Don't bother checking on devices
11666                // that don't have 64 bit support.
11667                boolean needsRenderScriptOverride = false;
11668                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11669                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11670                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11671                    needsRenderScriptOverride = true;
11672                }
11673
11674                final int copyRet;
11675                if (extractLibs) {
11676                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11677                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11678                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11679                } else {
11680                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11681                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11682                }
11683                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11684
11685                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11686                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11687                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11688                }
11689
11690                if (copyRet >= 0) {
11691                    // Shared libraries that have native libs must be multi-architecture
11692                    if (pkg.isLibrary()) {
11693                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11694                                "Shared library with native libs must be multiarch");
11695                    }
11696                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11697                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11698                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11699                } else if (needsRenderScriptOverride) {
11700                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11701                }
11702            }
11703        } catch (IOException ioe) {
11704            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11705        } finally {
11706            IoUtils.closeQuietly(handle);
11707        }
11708
11709        // Now that we've calculated the ABIs and determined if it's an internal app,
11710        // we will go ahead and populate the nativeLibraryPath.
11711        setNativeLibraryPaths(pkg, appLib32InstallDir);
11712    }
11713
11714    /**
11715     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11716     * i.e, so that all packages can be run inside a single process if required.
11717     *
11718     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11719     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11720     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11721     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11722     * updating a package that belongs to a shared user.
11723     *
11724     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11725     * adds unnecessary complexity.
11726     */
11727    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11728            PackageParser.Package scannedPackage) {
11729        String requiredInstructionSet = null;
11730        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11731            requiredInstructionSet = VMRuntime.getInstructionSet(
11732                     scannedPackage.applicationInfo.primaryCpuAbi);
11733        }
11734
11735        PackageSetting requirer = null;
11736        for (PackageSetting ps : packagesForUser) {
11737            // If packagesForUser contains scannedPackage, we skip it. This will happen
11738            // when scannedPackage is an update of an existing package. Without this check,
11739            // we will never be able to change the ABI of any package belonging to a shared
11740            // user, even if it's compatible with other packages.
11741            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11742                if (ps.primaryCpuAbiString == null) {
11743                    continue;
11744                }
11745
11746                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11747                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11748                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11749                    // this but there's not much we can do.
11750                    String errorMessage = "Instruction set mismatch, "
11751                            + ((requirer == null) ? "[caller]" : requirer)
11752                            + " requires " + requiredInstructionSet + " whereas " + ps
11753                            + " requires " + instructionSet;
11754                    Slog.w(TAG, errorMessage);
11755                }
11756
11757                if (requiredInstructionSet == null) {
11758                    requiredInstructionSet = instructionSet;
11759                    requirer = ps;
11760                }
11761            }
11762        }
11763
11764        if (requiredInstructionSet != null) {
11765            String adjustedAbi;
11766            if (requirer != null) {
11767                // requirer != null implies that either scannedPackage was null or that scannedPackage
11768                // did not require an ABI, in which case we have to adjust scannedPackage to match
11769                // the ABI of the set (which is the same as requirer's ABI)
11770                adjustedAbi = requirer.primaryCpuAbiString;
11771                if (scannedPackage != null) {
11772                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11773                }
11774            } else {
11775                // requirer == null implies that we're updating all ABIs in the set to
11776                // match scannedPackage.
11777                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11778            }
11779
11780            for (PackageSetting ps : packagesForUser) {
11781                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11782                    if (ps.primaryCpuAbiString != null) {
11783                        continue;
11784                    }
11785
11786                    ps.primaryCpuAbiString = adjustedAbi;
11787                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11788                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11789                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11790                        if (DEBUG_ABI_SELECTION) {
11791                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11792                                    + " (requirer="
11793                                    + (requirer != null ? requirer.pkg : "null")
11794                                    + ", scannedPackage="
11795                                    + (scannedPackage != null ? scannedPackage : "null")
11796                                    + ")");
11797                        }
11798                        try {
11799                            mInstaller.rmdex(ps.codePathString,
11800                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11801                        } catch (InstallerException ignored) {
11802                        }
11803                    }
11804                }
11805            }
11806        }
11807    }
11808
11809    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11810        synchronized (mPackages) {
11811            mResolverReplaced = true;
11812            // Set up information for custom user intent resolution activity.
11813            mResolveActivity.applicationInfo = pkg.applicationInfo;
11814            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11815            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11816            mResolveActivity.processName = pkg.applicationInfo.packageName;
11817            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11818            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11819                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11820            mResolveActivity.theme = 0;
11821            mResolveActivity.exported = true;
11822            mResolveActivity.enabled = true;
11823            mResolveInfo.activityInfo = mResolveActivity;
11824            mResolveInfo.priority = 0;
11825            mResolveInfo.preferredOrder = 0;
11826            mResolveInfo.match = 0;
11827            mResolveComponentName = mCustomResolverComponentName;
11828            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11829                    mResolveComponentName);
11830        }
11831    }
11832
11833    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11834        if (installerActivity == null) {
11835            if (DEBUG_EPHEMERAL) {
11836                Slog.d(TAG, "Clear ephemeral installer activity");
11837            }
11838            mInstantAppInstallerActivity = null;
11839            return;
11840        }
11841
11842        if (DEBUG_EPHEMERAL) {
11843            Slog.d(TAG, "Set ephemeral installer activity: "
11844                    + installerActivity.getComponentName());
11845        }
11846        // Set up information for ephemeral installer activity
11847        mInstantAppInstallerActivity = installerActivity;
11848        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11849                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11850        mInstantAppInstallerActivity.exported = true;
11851        mInstantAppInstallerActivity.enabled = true;
11852        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11853        mInstantAppInstallerInfo.priority = 0;
11854        mInstantAppInstallerInfo.preferredOrder = 1;
11855        mInstantAppInstallerInfo.isDefault = true;
11856        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11857                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11858    }
11859
11860    private static String calculateBundledApkRoot(final String codePathString) {
11861        final File codePath = new File(codePathString);
11862        final File codeRoot;
11863        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11864            codeRoot = Environment.getRootDirectory();
11865        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11866            codeRoot = Environment.getOemDirectory();
11867        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11868            codeRoot = Environment.getVendorDirectory();
11869        } else {
11870            // Unrecognized code path; take its top real segment as the apk root:
11871            // e.g. /something/app/blah.apk => /something
11872            try {
11873                File f = codePath.getCanonicalFile();
11874                File parent = f.getParentFile();    // non-null because codePath is a file
11875                File tmp;
11876                while ((tmp = parent.getParentFile()) != null) {
11877                    f = parent;
11878                    parent = tmp;
11879                }
11880                codeRoot = f;
11881                Slog.w(TAG, "Unrecognized code path "
11882                        + codePath + " - using " + codeRoot);
11883            } catch (IOException e) {
11884                // Can't canonicalize the code path -- shenanigans?
11885                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11886                return Environment.getRootDirectory().getPath();
11887            }
11888        }
11889        return codeRoot.getPath();
11890    }
11891
11892    /**
11893     * Derive and set the location of native libraries for the given package,
11894     * which varies depending on where and how the package was installed.
11895     */
11896    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11897        final ApplicationInfo info = pkg.applicationInfo;
11898        final String codePath = pkg.codePath;
11899        final File codeFile = new File(codePath);
11900        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11901        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11902
11903        info.nativeLibraryRootDir = null;
11904        info.nativeLibraryRootRequiresIsa = false;
11905        info.nativeLibraryDir = null;
11906        info.secondaryNativeLibraryDir = null;
11907
11908        if (isApkFile(codeFile)) {
11909            // Monolithic install
11910            if (bundledApp) {
11911                // If "/system/lib64/apkname" exists, assume that is the per-package
11912                // native library directory to use; otherwise use "/system/lib/apkname".
11913                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11914                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11915                        getPrimaryInstructionSet(info));
11916
11917                // This is a bundled system app so choose the path based on the ABI.
11918                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11919                // is just the default path.
11920                final String apkName = deriveCodePathName(codePath);
11921                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11922                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11923                        apkName).getAbsolutePath();
11924
11925                if (info.secondaryCpuAbi != null) {
11926                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11927                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11928                            secondaryLibDir, apkName).getAbsolutePath();
11929                }
11930            } else if (asecApp) {
11931                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11932                        .getAbsolutePath();
11933            } else {
11934                final String apkName = deriveCodePathName(codePath);
11935                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11936                        .getAbsolutePath();
11937            }
11938
11939            info.nativeLibraryRootRequiresIsa = false;
11940            info.nativeLibraryDir = info.nativeLibraryRootDir;
11941        } else {
11942            // Cluster install
11943            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11944            info.nativeLibraryRootRequiresIsa = true;
11945
11946            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11947                    getPrimaryInstructionSet(info)).getAbsolutePath();
11948
11949            if (info.secondaryCpuAbi != null) {
11950                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11951                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11952            }
11953        }
11954    }
11955
11956    /**
11957     * Calculate the abis and roots for a bundled app. These can uniquely
11958     * be determined from the contents of the system partition, i.e whether
11959     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11960     * of this information, and instead assume that the system was built
11961     * sensibly.
11962     */
11963    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11964                                           PackageSetting pkgSetting) {
11965        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11966
11967        // If "/system/lib64/apkname" exists, assume that is the per-package
11968        // native library directory to use; otherwise use "/system/lib/apkname".
11969        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11970        setBundledAppAbi(pkg, apkRoot, apkName);
11971        // pkgSetting might be null during rescan following uninstall of updates
11972        // to a bundled app, so accommodate that possibility.  The settings in
11973        // that case will be established later from the parsed package.
11974        //
11975        // If the settings aren't null, sync them up with what we've just derived.
11976        // note that apkRoot isn't stored in the package settings.
11977        if (pkgSetting != null) {
11978            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11979            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11980        }
11981    }
11982
11983    /**
11984     * Deduces the ABI of a bundled app and sets the relevant fields on the
11985     * parsed pkg object.
11986     *
11987     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11988     *        under which system libraries are installed.
11989     * @param apkName the name of the installed package.
11990     */
11991    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11992        final File codeFile = new File(pkg.codePath);
11993
11994        final boolean has64BitLibs;
11995        final boolean has32BitLibs;
11996        if (isApkFile(codeFile)) {
11997            // Monolithic install
11998            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11999            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12000        } else {
12001            // Cluster install
12002            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12003            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12004                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12005                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12006                has64BitLibs = (new File(rootDir, isa)).exists();
12007            } else {
12008                has64BitLibs = false;
12009            }
12010            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12011                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12012                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12013                has32BitLibs = (new File(rootDir, isa)).exists();
12014            } else {
12015                has32BitLibs = false;
12016            }
12017        }
12018
12019        if (has64BitLibs && !has32BitLibs) {
12020            // The package has 64 bit libs, but not 32 bit libs. Its primary
12021            // ABI should be 64 bit. We can safely assume here that the bundled
12022            // native libraries correspond to the most preferred ABI in the list.
12023
12024            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12025            pkg.applicationInfo.secondaryCpuAbi = null;
12026        } else if (has32BitLibs && !has64BitLibs) {
12027            // The package has 32 bit libs but not 64 bit libs. Its primary
12028            // ABI should be 32 bit.
12029
12030            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12031            pkg.applicationInfo.secondaryCpuAbi = null;
12032        } else if (has32BitLibs && has64BitLibs) {
12033            // The application has both 64 and 32 bit bundled libraries. We check
12034            // here that the app declares multiArch support, and warn if it doesn't.
12035            //
12036            // We will be lenient here and record both ABIs. The primary will be the
12037            // ABI that's higher on the list, i.e, a device that's configured to prefer
12038            // 64 bit apps will see a 64 bit primary ABI,
12039
12040            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12041                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12042            }
12043
12044            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12045                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12046                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12047            } else {
12048                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12049                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12050            }
12051        } else {
12052            pkg.applicationInfo.primaryCpuAbi = null;
12053            pkg.applicationInfo.secondaryCpuAbi = null;
12054        }
12055    }
12056
12057    private void killApplication(String pkgName, int appId, String reason) {
12058        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12059    }
12060
12061    private void killApplication(String pkgName, int appId, int userId, String reason) {
12062        // Request the ActivityManager to kill the process(only for existing packages)
12063        // so that we do not end up in a confused state while the user is still using the older
12064        // version of the application while the new one gets installed.
12065        final long token = Binder.clearCallingIdentity();
12066        try {
12067            IActivityManager am = ActivityManager.getService();
12068            if (am != null) {
12069                try {
12070                    am.killApplication(pkgName, appId, userId, reason);
12071                } catch (RemoteException e) {
12072                }
12073            }
12074        } finally {
12075            Binder.restoreCallingIdentity(token);
12076        }
12077    }
12078
12079    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12080        // Remove the parent package setting
12081        PackageSetting ps = (PackageSetting) pkg.mExtras;
12082        if (ps != null) {
12083            removePackageLI(ps, chatty);
12084        }
12085        // Remove the child package setting
12086        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12087        for (int i = 0; i < childCount; i++) {
12088            PackageParser.Package childPkg = pkg.childPackages.get(i);
12089            ps = (PackageSetting) childPkg.mExtras;
12090            if (ps != null) {
12091                removePackageLI(ps, chatty);
12092            }
12093        }
12094    }
12095
12096    void removePackageLI(PackageSetting ps, boolean chatty) {
12097        if (DEBUG_INSTALL) {
12098            if (chatty)
12099                Log.d(TAG, "Removing package " + ps.name);
12100        }
12101
12102        // writer
12103        synchronized (mPackages) {
12104            mPackages.remove(ps.name);
12105            final PackageParser.Package pkg = ps.pkg;
12106            if (pkg != null) {
12107                cleanPackageDataStructuresLILPw(pkg, chatty);
12108            }
12109        }
12110    }
12111
12112    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12113        if (DEBUG_INSTALL) {
12114            if (chatty)
12115                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12116        }
12117
12118        // writer
12119        synchronized (mPackages) {
12120            // Remove the parent package
12121            mPackages.remove(pkg.applicationInfo.packageName);
12122            cleanPackageDataStructuresLILPw(pkg, chatty);
12123
12124            // Remove the child packages
12125            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12126            for (int i = 0; i < childCount; i++) {
12127                PackageParser.Package childPkg = pkg.childPackages.get(i);
12128                mPackages.remove(childPkg.applicationInfo.packageName);
12129                cleanPackageDataStructuresLILPw(childPkg, chatty);
12130            }
12131        }
12132    }
12133
12134    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12135        int N = pkg.providers.size();
12136        StringBuilder r = null;
12137        int i;
12138        for (i=0; i<N; i++) {
12139            PackageParser.Provider p = pkg.providers.get(i);
12140            mProviders.removeProvider(p);
12141            if (p.info.authority == null) {
12142
12143                /* There was another ContentProvider with this authority when
12144                 * this app was installed so this authority is null,
12145                 * Ignore it as we don't have to unregister the provider.
12146                 */
12147                continue;
12148            }
12149            String names[] = p.info.authority.split(";");
12150            for (int j = 0; j < names.length; j++) {
12151                if (mProvidersByAuthority.get(names[j]) == p) {
12152                    mProvidersByAuthority.remove(names[j]);
12153                    if (DEBUG_REMOVE) {
12154                        if (chatty)
12155                            Log.d(TAG, "Unregistered content provider: " + names[j]
12156                                    + ", className = " + p.info.name + ", isSyncable = "
12157                                    + p.info.isSyncable);
12158                    }
12159                }
12160            }
12161            if (DEBUG_REMOVE && chatty) {
12162                if (r == null) {
12163                    r = new StringBuilder(256);
12164                } else {
12165                    r.append(' ');
12166                }
12167                r.append(p.info.name);
12168            }
12169        }
12170        if (r != null) {
12171            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12172        }
12173
12174        N = pkg.services.size();
12175        r = null;
12176        for (i=0; i<N; i++) {
12177            PackageParser.Service s = pkg.services.get(i);
12178            mServices.removeService(s);
12179            if (chatty) {
12180                if (r == null) {
12181                    r = new StringBuilder(256);
12182                } else {
12183                    r.append(' ');
12184                }
12185                r.append(s.info.name);
12186            }
12187        }
12188        if (r != null) {
12189            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12190        }
12191
12192        N = pkg.receivers.size();
12193        r = null;
12194        for (i=0; i<N; i++) {
12195            PackageParser.Activity a = pkg.receivers.get(i);
12196            mReceivers.removeActivity(a, "receiver");
12197            if (DEBUG_REMOVE && chatty) {
12198                if (r == null) {
12199                    r = new StringBuilder(256);
12200                } else {
12201                    r.append(' ');
12202                }
12203                r.append(a.info.name);
12204            }
12205        }
12206        if (r != null) {
12207            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12208        }
12209
12210        N = pkg.activities.size();
12211        r = null;
12212        for (i=0; i<N; i++) {
12213            PackageParser.Activity a = pkg.activities.get(i);
12214            mActivities.removeActivity(a, "activity");
12215            if (DEBUG_REMOVE && chatty) {
12216                if (r == null) {
12217                    r = new StringBuilder(256);
12218                } else {
12219                    r.append(' ');
12220                }
12221                r.append(a.info.name);
12222            }
12223        }
12224        if (r != null) {
12225            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12226        }
12227
12228        N = pkg.permissions.size();
12229        r = null;
12230        for (i=0; i<N; i++) {
12231            PackageParser.Permission p = pkg.permissions.get(i);
12232            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12233            if (bp == null) {
12234                bp = mSettings.mPermissionTrees.get(p.info.name);
12235            }
12236            if (bp != null && bp.perm == p) {
12237                bp.perm = null;
12238                if (DEBUG_REMOVE && chatty) {
12239                    if (r == null) {
12240                        r = new StringBuilder(256);
12241                    } else {
12242                        r.append(' ');
12243                    }
12244                    r.append(p.info.name);
12245                }
12246            }
12247            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12248                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12249                if (appOpPkgs != null) {
12250                    appOpPkgs.remove(pkg.packageName);
12251                }
12252            }
12253        }
12254        if (r != null) {
12255            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12256        }
12257
12258        N = pkg.requestedPermissions.size();
12259        r = null;
12260        for (i=0; i<N; i++) {
12261            String perm = pkg.requestedPermissions.get(i);
12262            BasePermission bp = mSettings.mPermissions.get(perm);
12263            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12264                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12265                if (appOpPkgs != null) {
12266                    appOpPkgs.remove(pkg.packageName);
12267                    if (appOpPkgs.isEmpty()) {
12268                        mAppOpPermissionPackages.remove(perm);
12269                    }
12270                }
12271            }
12272        }
12273        if (r != null) {
12274            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12275        }
12276
12277        N = pkg.instrumentation.size();
12278        r = null;
12279        for (i=0; i<N; i++) {
12280            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12281            mInstrumentation.remove(a.getComponentName());
12282            if (DEBUG_REMOVE && chatty) {
12283                if (r == null) {
12284                    r = new StringBuilder(256);
12285                } else {
12286                    r.append(' ');
12287                }
12288                r.append(a.info.name);
12289            }
12290        }
12291        if (r != null) {
12292            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12293        }
12294
12295        r = null;
12296        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12297            // Only system apps can hold shared libraries.
12298            if (pkg.libraryNames != null) {
12299                for (i = 0; i < pkg.libraryNames.size(); i++) {
12300                    String name = pkg.libraryNames.get(i);
12301                    if (removeSharedLibraryLPw(name, 0)) {
12302                        if (DEBUG_REMOVE && chatty) {
12303                            if (r == null) {
12304                                r = new StringBuilder(256);
12305                            } else {
12306                                r.append(' ');
12307                            }
12308                            r.append(name);
12309                        }
12310                    }
12311                }
12312            }
12313        }
12314
12315        r = null;
12316
12317        // Any package can hold static shared libraries.
12318        if (pkg.staticSharedLibName != null) {
12319            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12320                if (DEBUG_REMOVE && chatty) {
12321                    if (r == null) {
12322                        r = new StringBuilder(256);
12323                    } else {
12324                        r.append(' ');
12325                    }
12326                    r.append(pkg.staticSharedLibName);
12327                }
12328            }
12329        }
12330
12331        if (r != null) {
12332            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12333        }
12334    }
12335
12336    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12337        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12338            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12339                return true;
12340            }
12341        }
12342        return false;
12343    }
12344
12345    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12346    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12347    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12348
12349    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12350        // Update the parent permissions
12351        updatePermissionsLPw(pkg.packageName, pkg, flags);
12352        // Update the child permissions
12353        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12354        for (int i = 0; i < childCount; i++) {
12355            PackageParser.Package childPkg = pkg.childPackages.get(i);
12356            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12357        }
12358    }
12359
12360    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12361            int flags) {
12362        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12363        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12364    }
12365
12366    private void updatePermissionsLPw(String changingPkg,
12367            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12368        // Make sure there are no dangling permission trees.
12369        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12370        while (it.hasNext()) {
12371            final BasePermission bp = it.next();
12372            if (bp.packageSetting == null) {
12373                // We may not yet have parsed the package, so just see if
12374                // we still know about its settings.
12375                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12376            }
12377            if (bp.packageSetting == null) {
12378                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12379                        + " from package " + bp.sourcePackage);
12380                it.remove();
12381            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12382                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12383                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12384                            + " from package " + bp.sourcePackage);
12385                    flags |= UPDATE_PERMISSIONS_ALL;
12386                    it.remove();
12387                }
12388            }
12389        }
12390
12391        // Make sure all dynamic permissions have been assigned to a package,
12392        // and make sure there are no dangling permissions.
12393        it = mSettings.mPermissions.values().iterator();
12394        while (it.hasNext()) {
12395            final BasePermission bp = it.next();
12396            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12397                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12398                        + bp.name + " pkg=" + bp.sourcePackage
12399                        + " info=" + bp.pendingInfo);
12400                if (bp.packageSetting == null && bp.pendingInfo != null) {
12401                    final BasePermission tree = findPermissionTreeLP(bp.name);
12402                    if (tree != null && tree.perm != null) {
12403                        bp.packageSetting = tree.packageSetting;
12404                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12405                                new PermissionInfo(bp.pendingInfo));
12406                        bp.perm.info.packageName = tree.perm.info.packageName;
12407                        bp.perm.info.name = bp.name;
12408                        bp.uid = tree.uid;
12409                    }
12410                }
12411            }
12412            if (bp.packageSetting == null) {
12413                // We may not yet have parsed the package, so just see if
12414                // we still know about its settings.
12415                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12416            }
12417            if (bp.packageSetting == null) {
12418                Slog.w(TAG, "Removing dangling permission: " + bp.name
12419                        + " from package " + bp.sourcePackage);
12420                it.remove();
12421            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12422                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12423                    Slog.i(TAG, "Removing old permission: " + bp.name
12424                            + " from package " + bp.sourcePackage);
12425                    flags |= UPDATE_PERMISSIONS_ALL;
12426                    it.remove();
12427                }
12428            }
12429        }
12430
12431        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12432        // Now update the permissions for all packages, in particular
12433        // replace the granted permissions of the system packages.
12434        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12435            for (PackageParser.Package pkg : mPackages.values()) {
12436                if (pkg != pkgInfo) {
12437                    // Only replace for packages on requested volume
12438                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12439                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12440                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12441                    grantPermissionsLPw(pkg, replace, changingPkg);
12442                }
12443            }
12444        }
12445
12446        if (pkgInfo != null) {
12447            // Only replace for packages on requested volume
12448            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12449            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12450                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12451            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12452        }
12453        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12454    }
12455
12456    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12457            String packageOfInterest) {
12458        // IMPORTANT: There are two types of permissions: install and runtime.
12459        // Install time permissions are granted when the app is installed to
12460        // all device users and users added in the future. Runtime permissions
12461        // are granted at runtime explicitly to specific users. Normal and signature
12462        // protected permissions are install time permissions. Dangerous permissions
12463        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12464        // otherwise they are runtime permissions. This function does not manage
12465        // runtime permissions except for the case an app targeting Lollipop MR1
12466        // being upgraded to target a newer SDK, in which case dangerous permissions
12467        // are transformed from install time to runtime ones.
12468
12469        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12470        if (ps == null) {
12471            return;
12472        }
12473
12474        PermissionsState permissionsState = ps.getPermissionsState();
12475        PermissionsState origPermissions = permissionsState;
12476
12477        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12478
12479        boolean runtimePermissionsRevoked = false;
12480        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12481
12482        boolean changedInstallPermission = false;
12483
12484        if (replace) {
12485            ps.installPermissionsFixed = false;
12486            if (!ps.isSharedUser()) {
12487                origPermissions = new PermissionsState(permissionsState);
12488                permissionsState.reset();
12489            } else {
12490                // We need to know only about runtime permission changes since the
12491                // calling code always writes the install permissions state but
12492                // the runtime ones are written only if changed. The only cases of
12493                // changed runtime permissions here are promotion of an install to
12494                // runtime and revocation of a runtime from a shared user.
12495                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12496                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12497                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12498                    runtimePermissionsRevoked = true;
12499                }
12500            }
12501        }
12502
12503        permissionsState.setGlobalGids(mGlobalGids);
12504
12505        final int N = pkg.requestedPermissions.size();
12506        for (int i=0; i<N; i++) {
12507            final String name = pkg.requestedPermissions.get(i);
12508            final BasePermission bp = mSettings.mPermissions.get(name);
12509            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12510                    >= Build.VERSION_CODES.M;
12511
12512            if (DEBUG_INSTALL) {
12513                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12514            }
12515
12516            if (bp == null || bp.packageSetting == null) {
12517                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12518                    if (DEBUG_PERMISSIONS) {
12519                        Slog.i(TAG, "Unknown permission " + name
12520                                + " in package " + pkg.packageName);
12521                    }
12522                }
12523                continue;
12524            }
12525
12526
12527            // Limit ephemeral apps to ephemeral allowed permissions.
12528            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12529                if (DEBUG_PERMISSIONS) {
12530                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12531                            + pkg.packageName);
12532                }
12533                continue;
12534            }
12535
12536            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12537                if (DEBUG_PERMISSIONS) {
12538                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12539                            + pkg.packageName);
12540                }
12541                continue;
12542            }
12543
12544            final String perm = bp.name;
12545            boolean allowedSig = false;
12546            int grant = GRANT_DENIED;
12547
12548            // Keep track of app op permissions.
12549            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12550                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12551                if (pkgs == null) {
12552                    pkgs = new ArraySet<>();
12553                    mAppOpPermissionPackages.put(bp.name, pkgs);
12554                }
12555                pkgs.add(pkg.packageName);
12556            }
12557
12558            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12559            switch (level) {
12560                case PermissionInfo.PROTECTION_NORMAL: {
12561                    // For all apps normal permissions are install time ones.
12562                    grant = GRANT_INSTALL;
12563                } break;
12564
12565                case PermissionInfo.PROTECTION_DANGEROUS: {
12566                    // If a permission review is required for legacy apps we represent
12567                    // their permissions as always granted runtime ones since we need
12568                    // to keep the review required permission flag per user while an
12569                    // install permission's state is shared across all users.
12570                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12571                        // For legacy apps dangerous permissions are install time ones.
12572                        grant = GRANT_INSTALL;
12573                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12574                        // For legacy apps that became modern, install becomes runtime.
12575                        grant = GRANT_UPGRADE;
12576                    } else if (mPromoteSystemApps
12577                            && isSystemApp(ps)
12578                            && mExistingSystemPackages.contains(ps.name)) {
12579                        // For legacy system apps, install becomes runtime.
12580                        // We cannot check hasInstallPermission() for system apps since those
12581                        // permissions were granted implicitly and not persisted pre-M.
12582                        grant = GRANT_UPGRADE;
12583                    } else {
12584                        // For modern apps keep runtime permissions unchanged.
12585                        grant = GRANT_RUNTIME;
12586                    }
12587                } break;
12588
12589                case PermissionInfo.PROTECTION_SIGNATURE: {
12590                    // For all apps signature permissions are install time ones.
12591                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12592                    if (allowedSig) {
12593                        grant = GRANT_INSTALL;
12594                    }
12595                } break;
12596            }
12597
12598            if (DEBUG_PERMISSIONS) {
12599                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12600            }
12601
12602            if (grant != GRANT_DENIED) {
12603                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12604                    // If this is an existing, non-system package, then
12605                    // we can't add any new permissions to it.
12606                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12607                        // Except...  if this is a permission that was added
12608                        // to the platform (note: need to only do this when
12609                        // updating the platform).
12610                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12611                            grant = GRANT_DENIED;
12612                        }
12613                    }
12614                }
12615
12616                switch (grant) {
12617                    case GRANT_INSTALL: {
12618                        // Revoke this as runtime permission to handle the case of
12619                        // a runtime permission being downgraded to an install one.
12620                        // Also in permission review mode we keep dangerous permissions
12621                        // for legacy apps
12622                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12623                            if (origPermissions.getRuntimePermissionState(
12624                                    bp.name, userId) != null) {
12625                                // Revoke the runtime permission and clear the flags.
12626                                origPermissions.revokeRuntimePermission(bp, userId);
12627                                origPermissions.updatePermissionFlags(bp, userId,
12628                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12629                                // If we revoked a permission permission, we have to write.
12630                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12631                                        changedRuntimePermissionUserIds, userId);
12632                            }
12633                        }
12634                        // Grant an install permission.
12635                        if (permissionsState.grantInstallPermission(bp) !=
12636                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12637                            changedInstallPermission = true;
12638                        }
12639                    } break;
12640
12641                    case GRANT_RUNTIME: {
12642                        // Grant previously granted runtime permissions.
12643                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12644                            PermissionState permissionState = origPermissions
12645                                    .getRuntimePermissionState(bp.name, userId);
12646                            int flags = permissionState != null
12647                                    ? permissionState.getFlags() : 0;
12648                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12649                                // Don't propagate the permission in a permission review mode if
12650                                // the former was revoked, i.e. marked to not propagate on upgrade.
12651                                // Note that in a permission review mode install permissions are
12652                                // represented as constantly granted runtime ones since we need to
12653                                // keep a per user state associated with the permission. Also the
12654                                // revoke on upgrade flag is no longer applicable and is reset.
12655                                final boolean revokeOnUpgrade = (flags & PackageManager
12656                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12657                                if (revokeOnUpgrade) {
12658                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12659                                    // Since we changed the flags, we have to write.
12660                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12661                                            changedRuntimePermissionUserIds, userId);
12662                                }
12663                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12664                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12665                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12666                                        // If we cannot put the permission as it was,
12667                                        // we have to write.
12668                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12669                                                changedRuntimePermissionUserIds, userId);
12670                                    }
12671                                }
12672
12673                                // If the app supports runtime permissions no need for a review.
12674                                if (mPermissionReviewRequired
12675                                        && appSupportsRuntimePermissions
12676                                        && (flags & PackageManager
12677                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12678                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12679                                    // Since we changed the flags, we have to write.
12680                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12681                                            changedRuntimePermissionUserIds, userId);
12682                                }
12683                            } else if (mPermissionReviewRequired
12684                                    && !appSupportsRuntimePermissions) {
12685                                // For legacy apps that need a permission review, every new
12686                                // runtime permission is granted but it is pending a review.
12687                                // We also need to review only platform defined runtime
12688                                // permissions as these are the only ones the platform knows
12689                                // how to disable the API to simulate revocation as legacy
12690                                // apps don't expect to run with revoked permissions.
12691                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12692                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12693                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12694                                        // We changed the flags, hence have to write.
12695                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12696                                                changedRuntimePermissionUserIds, userId);
12697                                    }
12698                                }
12699                                if (permissionsState.grantRuntimePermission(bp, userId)
12700                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12701                                    // We changed the permission, hence have to write.
12702                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12703                                            changedRuntimePermissionUserIds, userId);
12704                                }
12705                            }
12706                            // Propagate the permission flags.
12707                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12708                        }
12709                    } break;
12710
12711                    case GRANT_UPGRADE: {
12712                        // Grant runtime permissions for a previously held install permission.
12713                        PermissionState permissionState = origPermissions
12714                                .getInstallPermissionState(bp.name);
12715                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12716
12717                        if (origPermissions.revokeInstallPermission(bp)
12718                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12719                            // We will be transferring the permission flags, so clear them.
12720                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12721                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12722                            changedInstallPermission = true;
12723                        }
12724
12725                        // If the permission is not to be promoted to runtime we ignore it and
12726                        // also its other flags as they are not applicable to install permissions.
12727                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12728                            for (int userId : currentUserIds) {
12729                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12730                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12731                                    // Transfer the permission flags.
12732                                    permissionsState.updatePermissionFlags(bp, userId,
12733                                            flags, flags);
12734                                    // If we granted the permission, we have to write.
12735                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12736                                            changedRuntimePermissionUserIds, userId);
12737                                }
12738                            }
12739                        }
12740                    } break;
12741
12742                    default: {
12743                        if (packageOfInterest == null
12744                                || packageOfInterest.equals(pkg.packageName)) {
12745                            if (DEBUG_PERMISSIONS) {
12746                                Slog.i(TAG, "Not granting permission " + perm
12747                                        + " to package " + pkg.packageName
12748                                        + " because it was previously installed without");
12749                            }
12750                        }
12751                    } break;
12752                }
12753            } else {
12754                if (permissionsState.revokeInstallPermission(bp) !=
12755                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12756                    // Also drop the permission flags.
12757                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12758                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12759                    changedInstallPermission = true;
12760                    Slog.i(TAG, "Un-granting permission " + perm
12761                            + " from package " + pkg.packageName
12762                            + " (protectionLevel=" + bp.protectionLevel
12763                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12764                            + ")");
12765                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12766                    // Don't print warning for app op permissions, since it is fine for them
12767                    // not to be granted, there is a UI for the user to decide.
12768                    if (DEBUG_PERMISSIONS
12769                            && (packageOfInterest == null
12770                                    || packageOfInterest.equals(pkg.packageName))) {
12771                        Slog.i(TAG, "Not granting permission " + perm
12772                                + " to package " + pkg.packageName
12773                                + " (protectionLevel=" + bp.protectionLevel
12774                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12775                                + ")");
12776                    }
12777                }
12778            }
12779        }
12780
12781        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12782                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12783            // This is the first that we have heard about this package, so the
12784            // permissions we have now selected are fixed until explicitly
12785            // changed.
12786            ps.installPermissionsFixed = true;
12787        }
12788
12789        // Persist the runtime permissions state for users with changes. If permissions
12790        // were revoked because no app in the shared user declares them we have to
12791        // write synchronously to avoid losing runtime permissions state.
12792        for (int userId : changedRuntimePermissionUserIds) {
12793            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12794        }
12795    }
12796
12797    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12798        boolean allowed = false;
12799        final int NP = PackageParser.NEW_PERMISSIONS.length;
12800        for (int ip=0; ip<NP; ip++) {
12801            final PackageParser.NewPermissionInfo npi
12802                    = PackageParser.NEW_PERMISSIONS[ip];
12803            if (npi.name.equals(perm)
12804                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12805                allowed = true;
12806                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12807                        + pkg.packageName);
12808                break;
12809            }
12810        }
12811        return allowed;
12812    }
12813
12814    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12815            BasePermission bp, PermissionsState origPermissions) {
12816        boolean privilegedPermission = (bp.protectionLevel
12817                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12818        boolean privappPermissionsDisable =
12819                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12820        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12821        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12822        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12823                && !platformPackage && platformPermission) {
12824            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12825                    .getPrivAppPermissions(pkg.packageName);
12826            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12827            if (!whitelisted) {
12828                Slog.w(TAG, "Privileged permission " + perm + " for package "
12829                        + pkg.packageName + " - not in privapp-permissions whitelist");
12830                // Only report violations for apps on system image
12831                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12832                    if (mPrivappPermissionsViolations == null) {
12833                        mPrivappPermissionsViolations = new ArraySet<>();
12834                    }
12835                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12836                }
12837                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12838                    return false;
12839                }
12840            }
12841        }
12842        boolean allowed = (compareSignatures(
12843                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12844                        == PackageManager.SIGNATURE_MATCH)
12845                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12846                        == PackageManager.SIGNATURE_MATCH);
12847        if (!allowed && privilegedPermission) {
12848            if (isSystemApp(pkg)) {
12849                // For updated system applications, a system permission
12850                // is granted only if it had been defined by the original application.
12851                if (pkg.isUpdatedSystemApp()) {
12852                    final PackageSetting sysPs = mSettings
12853                            .getDisabledSystemPkgLPr(pkg.packageName);
12854                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12855                        // If the original was granted this permission, we take
12856                        // that grant decision as read and propagate it to the
12857                        // update.
12858                        if (sysPs.isPrivileged()) {
12859                            allowed = true;
12860                        }
12861                    } else {
12862                        // The system apk may have been updated with an older
12863                        // version of the one on the data partition, but which
12864                        // granted a new system permission that it didn't have
12865                        // before.  In this case we do want to allow the app to
12866                        // now get the new permission if the ancestral apk is
12867                        // privileged to get it.
12868                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12869                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12870                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12871                                    allowed = true;
12872                                    break;
12873                                }
12874                            }
12875                        }
12876                        // Also if a privileged parent package on the system image or any of
12877                        // its children requested a privileged permission, the updated child
12878                        // packages can also get the permission.
12879                        if (pkg.parentPackage != null) {
12880                            final PackageSetting disabledSysParentPs = mSettings
12881                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12882                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12883                                    && disabledSysParentPs.isPrivileged()) {
12884                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12885                                    allowed = true;
12886                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12887                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12888                                    for (int i = 0; i < count; i++) {
12889                                        PackageParser.Package disabledSysChildPkg =
12890                                                disabledSysParentPs.pkg.childPackages.get(i);
12891                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12892                                                perm)) {
12893                                            allowed = true;
12894                                            break;
12895                                        }
12896                                    }
12897                                }
12898                            }
12899                        }
12900                    }
12901                } else {
12902                    allowed = isPrivilegedApp(pkg);
12903                }
12904            }
12905        }
12906        if (!allowed) {
12907            if (!allowed && (bp.protectionLevel
12908                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12909                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12910                // If this was a previously normal/dangerous permission that got moved
12911                // to a system permission as part of the runtime permission redesign, then
12912                // we still want to blindly grant it to old apps.
12913                allowed = true;
12914            }
12915            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12916                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12917                // If this permission is to be granted to the system installer and
12918                // this app is an installer, then it gets the permission.
12919                allowed = true;
12920            }
12921            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12922                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12923                // If this permission is to be granted to the system verifier and
12924                // this app is a verifier, then it gets the permission.
12925                allowed = true;
12926            }
12927            if (!allowed && (bp.protectionLevel
12928                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12929                    && isSystemApp(pkg)) {
12930                // Any pre-installed system app is allowed to get this permission.
12931                allowed = true;
12932            }
12933            if (!allowed && (bp.protectionLevel
12934                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12935                // For development permissions, a development permission
12936                // is granted only if it was already granted.
12937                allowed = origPermissions.hasInstallPermission(perm);
12938            }
12939            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12940                    && pkg.packageName.equals(mSetupWizardPackage)) {
12941                // If this permission is to be granted to the system setup wizard and
12942                // this app is a setup wizard, then it gets the permission.
12943                allowed = true;
12944            }
12945        }
12946        return allowed;
12947    }
12948
12949    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12950        final int permCount = pkg.requestedPermissions.size();
12951        for (int j = 0; j < permCount; j++) {
12952            String requestedPermission = pkg.requestedPermissions.get(j);
12953            if (permission.equals(requestedPermission)) {
12954                return true;
12955            }
12956        }
12957        return false;
12958    }
12959
12960    final class ActivityIntentResolver
12961            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12962        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12963                boolean defaultOnly, int userId) {
12964            if (!sUserManager.exists(userId)) return null;
12965            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12966            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12967        }
12968
12969        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12970                int userId) {
12971            if (!sUserManager.exists(userId)) return null;
12972            mFlags = flags;
12973            return super.queryIntent(intent, resolvedType,
12974                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12975                    userId);
12976        }
12977
12978        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12979                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12980            if (!sUserManager.exists(userId)) return null;
12981            if (packageActivities == null) {
12982                return null;
12983            }
12984            mFlags = flags;
12985            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12986            final int N = packageActivities.size();
12987            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12988                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12989
12990            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12991            for (int i = 0; i < N; ++i) {
12992                intentFilters = packageActivities.get(i).intents;
12993                if (intentFilters != null && intentFilters.size() > 0) {
12994                    PackageParser.ActivityIntentInfo[] array =
12995                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12996                    intentFilters.toArray(array);
12997                    listCut.add(array);
12998                }
12999            }
13000            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13001        }
13002
13003        /**
13004         * Finds a privileged activity that matches the specified activity names.
13005         */
13006        private PackageParser.Activity findMatchingActivity(
13007                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13008            for (PackageParser.Activity sysActivity : activityList) {
13009                if (sysActivity.info.name.equals(activityInfo.name)) {
13010                    return sysActivity;
13011                }
13012                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13013                    return sysActivity;
13014                }
13015                if (sysActivity.info.targetActivity != null) {
13016                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13017                        return sysActivity;
13018                    }
13019                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13020                        return sysActivity;
13021                    }
13022                }
13023            }
13024            return null;
13025        }
13026
13027        public class IterGenerator<E> {
13028            public Iterator<E> generate(ActivityIntentInfo info) {
13029                return null;
13030            }
13031        }
13032
13033        public class ActionIterGenerator extends IterGenerator<String> {
13034            @Override
13035            public Iterator<String> generate(ActivityIntentInfo info) {
13036                return info.actionsIterator();
13037            }
13038        }
13039
13040        public class CategoriesIterGenerator extends IterGenerator<String> {
13041            @Override
13042            public Iterator<String> generate(ActivityIntentInfo info) {
13043                return info.categoriesIterator();
13044            }
13045        }
13046
13047        public class SchemesIterGenerator extends IterGenerator<String> {
13048            @Override
13049            public Iterator<String> generate(ActivityIntentInfo info) {
13050                return info.schemesIterator();
13051            }
13052        }
13053
13054        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13055            @Override
13056            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13057                return info.authoritiesIterator();
13058            }
13059        }
13060
13061        /**
13062         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13063         * MODIFIED. Do not pass in a list that should not be changed.
13064         */
13065        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13066                IterGenerator<T> generator, Iterator<T> searchIterator) {
13067            // loop through the set of actions; every one must be found in the intent filter
13068            while (searchIterator.hasNext()) {
13069                // we must have at least one filter in the list to consider a match
13070                if (intentList.size() == 0) {
13071                    break;
13072                }
13073
13074                final T searchAction = searchIterator.next();
13075
13076                // loop through the set of intent filters
13077                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13078                while (intentIter.hasNext()) {
13079                    final ActivityIntentInfo intentInfo = intentIter.next();
13080                    boolean selectionFound = false;
13081
13082                    // loop through the intent filter's selection criteria; at least one
13083                    // of them must match the searched criteria
13084                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13085                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13086                        final T intentSelection = intentSelectionIter.next();
13087                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13088                            selectionFound = true;
13089                            break;
13090                        }
13091                    }
13092
13093                    // the selection criteria wasn't found in this filter's set; this filter
13094                    // is not a potential match
13095                    if (!selectionFound) {
13096                        intentIter.remove();
13097                    }
13098                }
13099            }
13100        }
13101
13102        private boolean isProtectedAction(ActivityIntentInfo filter) {
13103            final Iterator<String> actionsIter = filter.actionsIterator();
13104            while (actionsIter != null && actionsIter.hasNext()) {
13105                final String filterAction = actionsIter.next();
13106                if (PROTECTED_ACTIONS.contains(filterAction)) {
13107                    return true;
13108                }
13109            }
13110            return false;
13111        }
13112
13113        /**
13114         * Adjusts the priority of the given intent filter according to policy.
13115         * <p>
13116         * <ul>
13117         * <li>The priority for non privileged applications is capped to '0'</li>
13118         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13119         * <li>The priority for unbundled updates to privileged applications is capped to the
13120         *      priority defined on the system partition</li>
13121         * </ul>
13122         * <p>
13123         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13124         * allowed to obtain any priority on any action.
13125         */
13126        private void adjustPriority(
13127                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13128            // nothing to do; priority is fine as-is
13129            if (intent.getPriority() <= 0) {
13130                return;
13131            }
13132
13133            final ActivityInfo activityInfo = intent.activity.info;
13134            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13135
13136            final boolean privilegedApp =
13137                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13138            if (!privilegedApp) {
13139                // non-privileged applications can never define a priority >0
13140                if (DEBUG_FILTERS) {
13141                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13142                            + " package: " + applicationInfo.packageName
13143                            + " activity: " + intent.activity.className
13144                            + " origPrio: " + intent.getPriority());
13145                }
13146                intent.setPriority(0);
13147                return;
13148            }
13149
13150            if (systemActivities == null) {
13151                // the system package is not disabled; we're parsing the system partition
13152                if (isProtectedAction(intent)) {
13153                    if (mDeferProtectedFilters) {
13154                        // We can't deal with these just yet. No component should ever obtain a
13155                        // >0 priority for a protected actions, with ONE exception -- the setup
13156                        // wizard. The setup wizard, however, cannot be known until we're able to
13157                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13158                        // until all intent filters have been processed. Chicken, meet egg.
13159                        // Let the filter temporarily have a high priority and rectify the
13160                        // priorities after all system packages have been scanned.
13161                        mProtectedFilters.add(intent);
13162                        if (DEBUG_FILTERS) {
13163                            Slog.i(TAG, "Protected action; save for later;"
13164                                    + " package: " + applicationInfo.packageName
13165                                    + " activity: " + intent.activity.className
13166                                    + " origPrio: " + intent.getPriority());
13167                        }
13168                        return;
13169                    } else {
13170                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13171                            Slog.i(TAG, "No setup wizard;"
13172                                + " All protected intents capped to priority 0");
13173                        }
13174                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13175                            if (DEBUG_FILTERS) {
13176                                Slog.i(TAG, "Found setup wizard;"
13177                                    + " allow priority " + intent.getPriority() + ";"
13178                                    + " package: " + intent.activity.info.packageName
13179                                    + " activity: " + intent.activity.className
13180                                    + " priority: " + intent.getPriority());
13181                            }
13182                            // setup wizard gets whatever it wants
13183                            return;
13184                        }
13185                        if (DEBUG_FILTERS) {
13186                            Slog.i(TAG, "Protected action; cap priority to 0;"
13187                                    + " package: " + intent.activity.info.packageName
13188                                    + " activity: " + intent.activity.className
13189                                    + " origPrio: " + intent.getPriority());
13190                        }
13191                        intent.setPriority(0);
13192                        return;
13193                    }
13194                }
13195                // privileged apps on the system image get whatever priority they request
13196                return;
13197            }
13198
13199            // privileged app unbundled update ... try to find the same activity
13200            final PackageParser.Activity foundActivity =
13201                    findMatchingActivity(systemActivities, activityInfo);
13202            if (foundActivity == null) {
13203                // this is a new activity; it cannot obtain >0 priority
13204                if (DEBUG_FILTERS) {
13205                    Slog.i(TAG, "New activity; cap priority to 0;"
13206                            + " package: " + applicationInfo.packageName
13207                            + " activity: " + intent.activity.className
13208                            + " origPrio: " + intent.getPriority());
13209                }
13210                intent.setPriority(0);
13211                return;
13212            }
13213
13214            // found activity, now check for filter equivalence
13215
13216            // a shallow copy is enough; we modify the list, not its contents
13217            final List<ActivityIntentInfo> intentListCopy =
13218                    new ArrayList<>(foundActivity.intents);
13219            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13220
13221            // find matching action subsets
13222            final Iterator<String> actionsIterator = intent.actionsIterator();
13223            if (actionsIterator != null) {
13224                getIntentListSubset(
13225                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13226                if (intentListCopy.size() == 0) {
13227                    // no more intents to match; we're not equivalent
13228                    if (DEBUG_FILTERS) {
13229                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13230                                + " package: " + applicationInfo.packageName
13231                                + " activity: " + intent.activity.className
13232                                + " origPrio: " + intent.getPriority());
13233                    }
13234                    intent.setPriority(0);
13235                    return;
13236                }
13237            }
13238
13239            // find matching category subsets
13240            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13241            if (categoriesIterator != null) {
13242                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13243                        categoriesIterator);
13244                if (intentListCopy.size() == 0) {
13245                    // no more intents to match; we're not equivalent
13246                    if (DEBUG_FILTERS) {
13247                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13248                                + " package: " + applicationInfo.packageName
13249                                + " activity: " + intent.activity.className
13250                                + " origPrio: " + intent.getPriority());
13251                    }
13252                    intent.setPriority(0);
13253                    return;
13254                }
13255            }
13256
13257            // find matching schemes subsets
13258            final Iterator<String> schemesIterator = intent.schemesIterator();
13259            if (schemesIterator != null) {
13260                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13261                        schemesIterator);
13262                if (intentListCopy.size() == 0) {
13263                    // no more intents to match; we're not equivalent
13264                    if (DEBUG_FILTERS) {
13265                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13266                                + " package: " + applicationInfo.packageName
13267                                + " activity: " + intent.activity.className
13268                                + " origPrio: " + intent.getPriority());
13269                    }
13270                    intent.setPriority(0);
13271                    return;
13272                }
13273            }
13274
13275            // find matching authorities subsets
13276            final Iterator<IntentFilter.AuthorityEntry>
13277                    authoritiesIterator = intent.authoritiesIterator();
13278            if (authoritiesIterator != null) {
13279                getIntentListSubset(intentListCopy,
13280                        new AuthoritiesIterGenerator(),
13281                        authoritiesIterator);
13282                if (intentListCopy.size() == 0) {
13283                    // no more intents to match; we're not equivalent
13284                    if (DEBUG_FILTERS) {
13285                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13286                                + " package: " + applicationInfo.packageName
13287                                + " activity: " + intent.activity.className
13288                                + " origPrio: " + intent.getPriority());
13289                    }
13290                    intent.setPriority(0);
13291                    return;
13292                }
13293            }
13294
13295            // we found matching filter(s); app gets the max priority of all intents
13296            int cappedPriority = 0;
13297            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13298                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13299            }
13300            if (intent.getPriority() > cappedPriority) {
13301                if (DEBUG_FILTERS) {
13302                    Slog.i(TAG, "Found matching filter(s);"
13303                            + " cap priority to " + cappedPriority + ";"
13304                            + " package: " + applicationInfo.packageName
13305                            + " activity: " + intent.activity.className
13306                            + " origPrio: " + intent.getPriority());
13307                }
13308                intent.setPriority(cappedPriority);
13309                return;
13310            }
13311            // all this for nothing; the requested priority was <= what was on the system
13312        }
13313
13314        public final void addActivity(PackageParser.Activity a, String type) {
13315            mActivities.put(a.getComponentName(), a);
13316            if (DEBUG_SHOW_INFO)
13317                Log.v(
13318                TAG, "  " + type + " " +
13319                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13320            if (DEBUG_SHOW_INFO)
13321                Log.v(TAG, "    Class=" + a.info.name);
13322            final int NI = a.intents.size();
13323            for (int j=0; j<NI; j++) {
13324                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13325                if ("activity".equals(type)) {
13326                    final PackageSetting ps =
13327                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13328                    final List<PackageParser.Activity> systemActivities =
13329                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13330                    adjustPriority(systemActivities, intent);
13331                }
13332                if (DEBUG_SHOW_INFO) {
13333                    Log.v(TAG, "    IntentFilter:");
13334                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13335                }
13336                if (!intent.debugCheck()) {
13337                    Log.w(TAG, "==> For Activity " + a.info.name);
13338                }
13339                addFilter(intent);
13340            }
13341        }
13342
13343        public final void removeActivity(PackageParser.Activity a, String type) {
13344            mActivities.remove(a.getComponentName());
13345            if (DEBUG_SHOW_INFO) {
13346                Log.v(TAG, "  " + type + " "
13347                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13348                                : a.info.name) + ":");
13349                Log.v(TAG, "    Class=" + a.info.name);
13350            }
13351            final int NI = a.intents.size();
13352            for (int j=0; j<NI; j++) {
13353                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13354                if (DEBUG_SHOW_INFO) {
13355                    Log.v(TAG, "    IntentFilter:");
13356                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13357                }
13358                removeFilter(intent);
13359            }
13360        }
13361
13362        @Override
13363        protected boolean allowFilterResult(
13364                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13365            ActivityInfo filterAi = filter.activity.info;
13366            for (int i=dest.size()-1; i>=0; i--) {
13367                ActivityInfo destAi = dest.get(i).activityInfo;
13368                if (destAi.name == filterAi.name
13369                        && destAi.packageName == filterAi.packageName) {
13370                    return false;
13371                }
13372            }
13373            return true;
13374        }
13375
13376        @Override
13377        protected ActivityIntentInfo[] newArray(int size) {
13378            return new ActivityIntentInfo[size];
13379        }
13380
13381        @Override
13382        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13383            if (!sUserManager.exists(userId)) return true;
13384            PackageParser.Package p = filter.activity.owner;
13385            if (p != null) {
13386                PackageSetting ps = (PackageSetting)p.mExtras;
13387                if (ps != null) {
13388                    // System apps are never considered stopped for purposes of
13389                    // filtering, because there may be no way for the user to
13390                    // actually re-launch them.
13391                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13392                            && ps.getStopped(userId);
13393                }
13394            }
13395            return false;
13396        }
13397
13398        @Override
13399        protected boolean isPackageForFilter(String packageName,
13400                PackageParser.ActivityIntentInfo info) {
13401            return packageName.equals(info.activity.owner.packageName);
13402        }
13403
13404        @Override
13405        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13406                int match, int userId) {
13407            if (!sUserManager.exists(userId)) return null;
13408            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13409                return null;
13410            }
13411            final PackageParser.Activity activity = info.activity;
13412            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13413            if (ps == null) {
13414                return null;
13415            }
13416            final PackageUserState userState = ps.readUserState(userId);
13417            ActivityInfo ai =
13418                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13419            if (ai == null) {
13420                return null;
13421            }
13422            final boolean matchExplicitlyVisibleOnly =
13423                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13424            final boolean matchVisibleToInstantApp =
13425                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13426            final boolean componentVisible =
13427                    matchVisibleToInstantApp
13428                    && info.isVisibleToInstantApp()
13429                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13430            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13431            // throw out filters that aren't visible to ephemeral apps
13432            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13433                return null;
13434            }
13435            // throw out instant app filters if we're not explicitly requesting them
13436            if (!matchInstantApp && userState.instantApp) {
13437                return null;
13438            }
13439            // throw out instant app filters if updates are available; will trigger
13440            // instant app resolution
13441            if (userState.instantApp && ps.isUpdateAvailable()) {
13442                return null;
13443            }
13444            final ResolveInfo res = new ResolveInfo();
13445            res.activityInfo = ai;
13446            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13447                res.filter = info;
13448            }
13449            if (info != null) {
13450                res.handleAllWebDataURI = info.handleAllWebDataURI();
13451            }
13452            res.priority = info.getPriority();
13453            res.preferredOrder = activity.owner.mPreferredOrder;
13454            //System.out.println("Result: " + res.activityInfo.className +
13455            //                   " = " + res.priority);
13456            res.match = match;
13457            res.isDefault = info.hasDefault;
13458            res.labelRes = info.labelRes;
13459            res.nonLocalizedLabel = info.nonLocalizedLabel;
13460            if (userNeedsBadging(userId)) {
13461                res.noResourceId = true;
13462            } else {
13463                res.icon = info.icon;
13464            }
13465            res.iconResourceId = info.icon;
13466            res.system = res.activityInfo.applicationInfo.isSystemApp();
13467            res.isInstantAppAvailable = userState.instantApp;
13468            return res;
13469        }
13470
13471        @Override
13472        protected void sortResults(List<ResolveInfo> results) {
13473            Collections.sort(results, mResolvePrioritySorter);
13474        }
13475
13476        @Override
13477        protected void dumpFilter(PrintWriter out, String prefix,
13478                PackageParser.ActivityIntentInfo filter) {
13479            out.print(prefix); out.print(
13480                    Integer.toHexString(System.identityHashCode(filter.activity)));
13481                    out.print(' ');
13482                    filter.activity.printComponentShortName(out);
13483                    out.print(" filter ");
13484                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13485        }
13486
13487        @Override
13488        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13489            return filter.activity;
13490        }
13491
13492        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13493            PackageParser.Activity activity = (PackageParser.Activity)label;
13494            out.print(prefix); out.print(
13495                    Integer.toHexString(System.identityHashCode(activity)));
13496                    out.print(' ');
13497                    activity.printComponentShortName(out);
13498            if (count > 1) {
13499                out.print(" ("); out.print(count); out.print(" filters)");
13500            }
13501            out.println();
13502        }
13503
13504        // Keys are String (activity class name), values are Activity.
13505        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13506                = new ArrayMap<ComponentName, PackageParser.Activity>();
13507        private int mFlags;
13508    }
13509
13510    private final class ServiceIntentResolver
13511            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13512        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13513                boolean defaultOnly, int userId) {
13514            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13515            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13516        }
13517
13518        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13519                int userId) {
13520            if (!sUserManager.exists(userId)) return null;
13521            mFlags = flags;
13522            return super.queryIntent(intent, resolvedType,
13523                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13524                    userId);
13525        }
13526
13527        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13528                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13529            if (!sUserManager.exists(userId)) return null;
13530            if (packageServices == null) {
13531                return null;
13532            }
13533            mFlags = flags;
13534            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13535            final int N = packageServices.size();
13536            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13537                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13538
13539            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13540            for (int i = 0; i < N; ++i) {
13541                intentFilters = packageServices.get(i).intents;
13542                if (intentFilters != null && intentFilters.size() > 0) {
13543                    PackageParser.ServiceIntentInfo[] array =
13544                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13545                    intentFilters.toArray(array);
13546                    listCut.add(array);
13547                }
13548            }
13549            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13550        }
13551
13552        public final void addService(PackageParser.Service s) {
13553            mServices.put(s.getComponentName(), s);
13554            if (DEBUG_SHOW_INFO) {
13555                Log.v(TAG, "  "
13556                        + (s.info.nonLocalizedLabel != null
13557                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13558                Log.v(TAG, "    Class=" + s.info.name);
13559            }
13560            final int NI = s.intents.size();
13561            int j;
13562            for (j=0; j<NI; j++) {
13563                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13564                if (DEBUG_SHOW_INFO) {
13565                    Log.v(TAG, "    IntentFilter:");
13566                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13567                }
13568                if (!intent.debugCheck()) {
13569                    Log.w(TAG, "==> For Service " + s.info.name);
13570                }
13571                addFilter(intent);
13572            }
13573        }
13574
13575        public final void removeService(PackageParser.Service s) {
13576            mServices.remove(s.getComponentName());
13577            if (DEBUG_SHOW_INFO) {
13578                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13579                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13580                Log.v(TAG, "    Class=" + s.info.name);
13581            }
13582            final int NI = s.intents.size();
13583            int j;
13584            for (j=0; j<NI; j++) {
13585                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13586                if (DEBUG_SHOW_INFO) {
13587                    Log.v(TAG, "    IntentFilter:");
13588                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13589                }
13590                removeFilter(intent);
13591            }
13592        }
13593
13594        @Override
13595        protected boolean allowFilterResult(
13596                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13597            ServiceInfo filterSi = filter.service.info;
13598            for (int i=dest.size()-1; i>=0; i--) {
13599                ServiceInfo destAi = dest.get(i).serviceInfo;
13600                if (destAi.name == filterSi.name
13601                        && destAi.packageName == filterSi.packageName) {
13602                    return false;
13603                }
13604            }
13605            return true;
13606        }
13607
13608        @Override
13609        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13610            return new PackageParser.ServiceIntentInfo[size];
13611        }
13612
13613        @Override
13614        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13615            if (!sUserManager.exists(userId)) return true;
13616            PackageParser.Package p = filter.service.owner;
13617            if (p != null) {
13618                PackageSetting ps = (PackageSetting)p.mExtras;
13619                if (ps != null) {
13620                    // System apps are never considered stopped for purposes of
13621                    // filtering, because there may be no way for the user to
13622                    // actually re-launch them.
13623                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13624                            && ps.getStopped(userId);
13625                }
13626            }
13627            return false;
13628        }
13629
13630        @Override
13631        protected boolean isPackageForFilter(String packageName,
13632                PackageParser.ServiceIntentInfo info) {
13633            return packageName.equals(info.service.owner.packageName);
13634        }
13635
13636        @Override
13637        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13638                int match, int userId) {
13639            if (!sUserManager.exists(userId)) return null;
13640            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13641            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13642                return null;
13643            }
13644            final PackageParser.Service service = info.service;
13645            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13646            if (ps == null) {
13647                return null;
13648            }
13649            final PackageUserState userState = ps.readUserState(userId);
13650            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13651                    userState, userId);
13652            if (si == null) {
13653                return null;
13654            }
13655            final boolean matchVisibleToInstantApp =
13656                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13657            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13658            // throw out filters that aren't visible to ephemeral apps
13659            if (matchVisibleToInstantApp
13660                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13661                return null;
13662            }
13663            // throw out ephemeral filters if we're not explicitly requesting them
13664            if (!isInstantApp && userState.instantApp) {
13665                return null;
13666            }
13667            // throw out instant app filters if updates are available; will trigger
13668            // instant app resolution
13669            if (userState.instantApp && ps.isUpdateAvailable()) {
13670                return null;
13671            }
13672            final ResolveInfo res = new ResolveInfo();
13673            res.serviceInfo = si;
13674            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13675                res.filter = filter;
13676            }
13677            res.priority = info.getPriority();
13678            res.preferredOrder = service.owner.mPreferredOrder;
13679            res.match = match;
13680            res.isDefault = info.hasDefault;
13681            res.labelRes = info.labelRes;
13682            res.nonLocalizedLabel = info.nonLocalizedLabel;
13683            res.icon = info.icon;
13684            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13685            return res;
13686        }
13687
13688        @Override
13689        protected void sortResults(List<ResolveInfo> results) {
13690            Collections.sort(results, mResolvePrioritySorter);
13691        }
13692
13693        @Override
13694        protected void dumpFilter(PrintWriter out, String prefix,
13695                PackageParser.ServiceIntentInfo filter) {
13696            out.print(prefix); out.print(
13697                    Integer.toHexString(System.identityHashCode(filter.service)));
13698                    out.print(' ');
13699                    filter.service.printComponentShortName(out);
13700                    out.print(" filter ");
13701                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13702        }
13703
13704        @Override
13705        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13706            return filter.service;
13707        }
13708
13709        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13710            PackageParser.Service service = (PackageParser.Service)label;
13711            out.print(prefix); out.print(
13712                    Integer.toHexString(System.identityHashCode(service)));
13713                    out.print(' ');
13714                    service.printComponentShortName(out);
13715            if (count > 1) {
13716                out.print(" ("); out.print(count); out.print(" filters)");
13717            }
13718            out.println();
13719        }
13720
13721//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13722//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13723//            final List<ResolveInfo> retList = Lists.newArrayList();
13724//            while (i.hasNext()) {
13725//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13726//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13727//                    retList.add(resolveInfo);
13728//                }
13729//            }
13730//            return retList;
13731//        }
13732
13733        // Keys are String (activity class name), values are Activity.
13734        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13735                = new ArrayMap<ComponentName, PackageParser.Service>();
13736        private int mFlags;
13737    }
13738
13739    private final class ProviderIntentResolver
13740            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13741        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13742                boolean defaultOnly, int userId) {
13743            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13744            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13745        }
13746
13747        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13748                int userId) {
13749            if (!sUserManager.exists(userId))
13750                return null;
13751            mFlags = flags;
13752            return super.queryIntent(intent, resolvedType,
13753                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13754                    userId);
13755        }
13756
13757        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13758                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13759            if (!sUserManager.exists(userId))
13760                return null;
13761            if (packageProviders == null) {
13762                return null;
13763            }
13764            mFlags = flags;
13765            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13766            final int N = packageProviders.size();
13767            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13768                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13769
13770            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13771            for (int i = 0; i < N; ++i) {
13772                intentFilters = packageProviders.get(i).intents;
13773                if (intentFilters != null && intentFilters.size() > 0) {
13774                    PackageParser.ProviderIntentInfo[] array =
13775                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13776                    intentFilters.toArray(array);
13777                    listCut.add(array);
13778                }
13779            }
13780            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13781        }
13782
13783        public final void addProvider(PackageParser.Provider p) {
13784            if (mProviders.containsKey(p.getComponentName())) {
13785                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13786                return;
13787            }
13788
13789            mProviders.put(p.getComponentName(), p);
13790            if (DEBUG_SHOW_INFO) {
13791                Log.v(TAG, "  "
13792                        + (p.info.nonLocalizedLabel != null
13793                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13794                Log.v(TAG, "    Class=" + p.info.name);
13795            }
13796            final int NI = p.intents.size();
13797            int j;
13798            for (j = 0; j < NI; j++) {
13799                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13800                if (DEBUG_SHOW_INFO) {
13801                    Log.v(TAG, "    IntentFilter:");
13802                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13803                }
13804                if (!intent.debugCheck()) {
13805                    Log.w(TAG, "==> For Provider " + p.info.name);
13806                }
13807                addFilter(intent);
13808            }
13809        }
13810
13811        public final void removeProvider(PackageParser.Provider p) {
13812            mProviders.remove(p.getComponentName());
13813            if (DEBUG_SHOW_INFO) {
13814                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13815                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13816                Log.v(TAG, "    Class=" + p.info.name);
13817            }
13818            final int NI = p.intents.size();
13819            int j;
13820            for (j = 0; j < NI; j++) {
13821                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13822                if (DEBUG_SHOW_INFO) {
13823                    Log.v(TAG, "    IntentFilter:");
13824                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13825                }
13826                removeFilter(intent);
13827            }
13828        }
13829
13830        @Override
13831        protected boolean allowFilterResult(
13832                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13833            ProviderInfo filterPi = filter.provider.info;
13834            for (int i = dest.size() - 1; i >= 0; i--) {
13835                ProviderInfo destPi = dest.get(i).providerInfo;
13836                if (destPi.name == filterPi.name
13837                        && destPi.packageName == filterPi.packageName) {
13838                    return false;
13839                }
13840            }
13841            return true;
13842        }
13843
13844        @Override
13845        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13846            return new PackageParser.ProviderIntentInfo[size];
13847        }
13848
13849        @Override
13850        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13851            if (!sUserManager.exists(userId))
13852                return true;
13853            PackageParser.Package p = filter.provider.owner;
13854            if (p != null) {
13855                PackageSetting ps = (PackageSetting) p.mExtras;
13856                if (ps != null) {
13857                    // System apps are never considered stopped for purposes of
13858                    // filtering, because there may be no way for the user to
13859                    // actually re-launch them.
13860                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13861                            && ps.getStopped(userId);
13862                }
13863            }
13864            return false;
13865        }
13866
13867        @Override
13868        protected boolean isPackageForFilter(String packageName,
13869                PackageParser.ProviderIntentInfo info) {
13870            return packageName.equals(info.provider.owner.packageName);
13871        }
13872
13873        @Override
13874        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13875                int match, int userId) {
13876            if (!sUserManager.exists(userId))
13877                return null;
13878            final PackageParser.ProviderIntentInfo info = filter;
13879            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13880                return null;
13881            }
13882            final PackageParser.Provider provider = info.provider;
13883            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13884            if (ps == null) {
13885                return null;
13886            }
13887            final PackageUserState userState = ps.readUserState(userId);
13888            final boolean matchVisibleToInstantApp =
13889                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13890            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13891            // throw out filters that aren't visible to instant applications
13892            if (matchVisibleToInstantApp
13893                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13894                return null;
13895            }
13896            // throw out instant application filters if we're not explicitly requesting them
13897            if (!isInstantApp && userState.instantApp) {
13898                return null;
13899            }
13900            // throw out instant application filters if updates are available; will trigger
13901            // instant application resolution
13902            if (userState.instantApp && ps.isUpdateAvailable()) {
13903                return null;
13904            }
13905            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13906                    userState, userId);
13907            if (pi == null) {
13908                return null;
13909            }
13910            final ResolveInfo res = new ResolveInfo();
13911            res.providerInfo = pi;
13912            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13913                res.filter = filter;
13914            }
13915            res.priority = info.getPriority();
13916            res.preferredOrder = provider.owner.mPreferredOrder;
13917            res.match = match;
13918            res.isDefault = info.hasDefault;
13919            res.labelRes = info.labelRes;
13920            res.nonLocalizedLabel = info.nonLocalizedLabel;
13921            res.icon = info.icon;
13922            res.system = res.providerInfo.applicationInfo.isSystemApp();
13923            return res;
13924        }
13925
13926        @Override
13927        protected void sortResults(List<ResolveInfo> results) {
13928            Collections.sort(results, mResolvePrioritySorter);
13929        }
13930
13931        @Override
13932        protected void dumpFilter(PrintWriter out, String prefix,
13933                PackageParser.ProviderIntentInfo filter) {
13934            out.print(prefix);
13935            out.print(
13936                    Integer.toHexString(System.identityHashCode(filter.provider)));
13937            out.print(' ');
13938            filter.provider.printComponentShortName(out);
13939            out.print(" filter ");
13940            out.println(Integer.toHexString(System.identityHashCode(filter)));
13941        }
13942
13943        @Override
13944        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13945            return filter.provider;
13946        }
13947
13948        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13949            PackageParser.Provider provider = (PackageParser.Provider)label;
13950            out.print(prefix); out.print(
13951                    Integer.toHexString(System.identityHashCode(provider)));
13952                    out.print(' ');
13953                    provider.printComponentShortName(out);
13954            if (count > 1) {
13955                out.print(" ("); out.print(count); out.print(" filters)");
13956            }
13957            out.println();
13958        }
13959
13960        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13961                = new ArrayMap<ComponentName, PackageParser.Provider>();
13962        private int mFlags;
13963    }
13964
13965    static final class EphemeralIntentResolver
13966            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13967        /**
13968         * The result that has the highest defined order. Ordering applies on a
13969         * per-package basis. Mapping is from package name to Pair of order and
13970         * EphemeralResolveInfo.
13971         * <p>
13972         * NOTE: This is implemented as a field variable for convenience and efficiency.
13973         * By having a field variable, we're able to track filter ordering as soon as
13974         * a non-zero order is defined. Otherwise, multiple loops across the result set
13975         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13976         * this needs to be contained entirely within {@link #filterResults}.
13977         */
13978        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13979
13980        @Override
13981        protected AuxiliaryResolveInfo[] newArray(int size) {
13982            return new AuxiliaryResolveInfo[size];
13983        }
13984
13985        @Override
13986        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13987            return true;
13988        }
13989
13990        @Override
13991        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13992                int userId) {
13993            if (!sUserManager.exists(userId)) {
13994                return null;
13995            }
13996            final String packageName = responseObj.resolveInfo.getPackageName();
13997            final Integer order = responseObj.getOrder();
13998            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13999                    mOrderResult.get(packageName);
14000            // ordering is enabled and this item's order isn't high enough
14001            if (lastOrderResult != null && lastOrderResult.first >= order) {
14002                return null;
14003            }
14004            final InstantAppResolveInfo res = responseObj.resolveInfo;
14005            if (order > 0) {
14006                // non-zero order, enable ordering
14007                mOrderResult.put(packageName, new Pair<>(order, res));
14008            }
14009            return responseObj;
14010        }
14011
14012        @Override
14013        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14014            // only do work if ordering is enabled [most of the time it won't be]
14015            if (mOrderResult.size() == 0) {
14016                return;
14017            }
14018            int resultSize = results.size();
14019            for (int i = 0; i < resultSize; i++) {
14020                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14021                final String packageName = info.getPackageName();
14022                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14023                if (savedInfo == null) {
14024                    // package doesn't having ordering
14025                    continue;
14026                }
14027                if (savedInfo.second == info) {
14028                    // circled back to the highest ordered item; remove from order list
14029                    mOrderResult.remove(savedInfo);
14030                    if (mOrderResult.size() == 0) {
14031                        // no more ordered items
14032                        break;
14033                    }
14034                    continue;
14035                }
14036                // item has a worse order, remove it from the result list
14037                results.remove(i);
14038                resultSize--;
14039                i--;
14040            }
14041        }
14042    }
14043
14044    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14045            new Comparator<ResolveInfo>() {
14046        public int compare(ResolveInfo r1, ResolveInfo r2) {
14047            int v1 = r1.priority;
14048            int v2 = r2.priority;
14049            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14050            if (v1 != v2) {
14051                return (v1 > v2) ? -1 : 1;
14052            }
14053            v1 = r1.preferredOrder;
14054            v2 = r2.preferredOrder;
14055            if (v1 != v2) {
14056                return (v1 > v2) ? -1 : 1;
14057            }
14058            if (r1.isDefault != r2.isDefault) {
14059                return r1.isDefault ? -1 : 1;
14060            }
14061            v1 = r1.match;
14062            v2 = r2.match;
14063            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14064            if (v1 != v2) {
14065                return (v1 > v2) ? -1 : 1;
14066            }
14067            if (r1.system != r2.system) {
14068                return r1.system ? -1 : 1;
14069            }
14070            if (r1.activityInfo != null) {
14071                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14072            }
14073            if (r1.serviceInfo != null) {
14074                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14075            }
14076            if (r1.providerInfo != null) {
14077                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14078            }
14079            return 0;
14080        }
14081    };
14082
14083    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14084            new Comparator<ProviderInfo>() {
14085        public int compare(ProviderInfo p1, ProviderInfo p2) {
14086            final int v1 = p1.initOrder;
14087            final int v2 = p2.initOrder;
14088            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14089        }
14090    };
14091
14092    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14093            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14094            final int[] userIds) {
14095        mHandler.post(new Runnable() {
14096            @Override
14097            public void run() {
14098                try {
14099                    final IActivityManager am = ActivityManager.getService();
14100                    if (am == null) return;
14101                    final int[] resolvedUserIds;
14102                    if (userIds == null) {
14103                        resolvedUserIds = am.getRunningUserIds();
14104                    } else {
14105                        resolvedUserIds = userIds;
14106                    }
14107                    for (int id : resolvedUserIds) {
14108                        final Intent intent = new Intent(action,
14109                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14110                        if (extras != null) {
14111                            intent.putExtras(extras);
14112                        }
14113                        if (targetPkg != null) {
14114                            intent.setPackage(targetPkg);
14115                        }
14116                        // Modify the UID when posting to other users
14117                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14118                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14119                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14120                            intent.putExtra(Intent.EXTRA_UID, uid);
14121                        }
14122                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14123                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14124                        if (DEBUG_BROADCASTS) {
14125                            RuntimeException here = new RuntimeException("here");
14126                            here.fillInStackTrace();
14127                            Slog.d(TAG, "Sending to user " + id + ": "
14128                                    + intent.toShortString(false, true, false, false)
14129                                    + " " + intent.getExtras(), here);
14130                        }
14131                        am.broadcastIntent(null, intent, null, finishedReceiver,
14132                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14133                                null, finishedReceiver != null, false, id);
14134                    }
14135                } catch (RemoteException ex) {
14136                }
14137            }
14138        });
14139    }
14140
14141    /**
14142     * Check if the external storage media is available. This is true if there
14143     * is a mounted external storage medium or if the external storage is
14144     * emulated.
14145     */
14146    private boolean isExternalMediaAvailable() {
14147        return mMediaMounted || Environment.isExternalStorageEmulated();
14148    }
14149
14150    @Override
14151    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14152        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14153            return null;
14154        }
14155        if (!isExternalMediaAvailable()) {
14156                // If the external storage is no longer mounted at this point,
14157                // the caller may not have been able to delete all of this
14158                // packages files and can not delete any more.  Bail.
14159            return null;
14160        }
14161        synchronized (mPackages) {
14162            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14163            if (lastPackage != null) {
14164                pkgs.remove(lastPackage);
14165            }
14166            if (pkgs.size() > 0) {
14167                return pkgs.get(0);
14168            }
14169        }
14170        return null;
14171    }
14172
14173    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14174        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14175                userId, andCode ? 1 : 0, packageName);
14176        if (mSystemReady) {
14177            msg.sendToTarget();
14178        } else {
14179            if (mPostSystemReadyMessages == null) {
14180                mPostSystemReadyMessages = new ArrayList<>();
14181            }
14182            mPostSystemReadyMessages.add(msg);
14183        }
14184    }
14185
14186    void startCleaningPackages() {
14187        // reader
14188        if (!isExternalMediaAvailable()) {
14189            return;
14190        }
14191        synchronized (mPackages) {
14192            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14193                return;
14194            }
14195        }
14196        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14197        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14198        IActivityManager am = ActivityManager.getService();
14199        if (am != null) {
14200            int dcsUid = -1;
14201            synchronized (mPackages) {
14202                if (!mDefaultContainerWhitelisted) {
14203                    mDefaultContainerWhitelisted = true;
14204                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14205                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14206                }
14207            }
14208            try {
14209                if (dcsUid > 0) {
14210                    am.backgroundWhitelistUid(dcsUid);
14211                }
14212                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14213                        UserHandle.USER_SYSTEM);
14214            } catch (RemoteException e) {
14215            }
14216        }
14217    }
14218
14219    @Override
14220    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14221            int installFlags, String installerPackageName, int userId) {
14222        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14223
14224        final int callingUid = Binder.getCallingUid();
14225        enforceCrossUserPermission(callingUid, userId,
14226                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14227
14228        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14229            try {
14230                if (observer != null) {
14231                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14232                }
14233            } catch (RemoteException re) {
14234            }
14235            return;
14236        }
14237
14238        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14239            installFlags |= PackageManager.INSTALL_FROM_ADB;
14240
14241        } else {
14242            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14243            // about installerPackageName.
14244
14245            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14246            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14247        }
14248
14249        UserHandle user;
14250        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14251            user = UserHandle.ALL;
14252        } else {
14253            user = new UserHandle(userId);
14254        }
14255
14256        // Only system components can circumvent runtime permissions when installing.
14257        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14258                && mContext.checkCallingOrSelfPermission(Manifest.permission
14259                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14260            throw new SecurityException("You need the "
14261                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14262                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14263        }
14264
14265        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14266                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14267            throw new IllegalArgumentException(
14268                    "New installs into ASEC containers no longer supported");
14269        }
14270
14271        final File originFile = new File(originPath);
14272        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14273
14274        final Message msg = mHandler.obtainMessage(INIT_COPY);
14275        final VerificationInfo verificationInfo = new VerificationInfo(
14276                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14277        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14278                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14279                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14280                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14281        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14282        msg.obj = params;
14283
14284        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14285                System.identityHashCode(msg.obj));
14286        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14287                System.identityHashCode(msg.obj));
14288
14289        mHandler.sendMessage(msg);
14290    }
14291
14292
14293    /**
14294     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14295     * it is acting on behalf on an enterprise or the user).
14296     *
14297     * Note that the ordering of the conditionals in this method is important. The checks we perform
14298     * are as follows, in this order:
14299     *
14300     * 1) If the install is being performed by a system app, we can trust the app to have set the
14301     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14302     *    what it is.
14303     * 2) If the install is being performed by a device or profile owner app, the install reason
14304     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14305     *    set the install reason correctly. If the app targets an older SDK version where install
14306     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14307     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14308     * 3) In all other cases, the install is being performed by a regular app that is neither part
14309     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14310     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14311     *    set to enterprise policy and if so, change it to unknown instead.
14312     */
14313    private int fixUpInstallReason(String installerPackageName, int installerUid,
14314            int installReason) {
14315        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14316                == PERMISSION_GRANTED) {
14317            // If the install is being performed by a system app, we trust that app to have set the
14318            // install reason correctly.
14319            return installReason;
14320        }
14321
14322        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14323            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14324        if (dpm != null) {
14325            ComponentName owner = null;
14326            try {
14327                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14328                if (owner == null) {
14329                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14330                }
14331            } catch (RemoteException e) {
14332            }
14333            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14334                // If the install is being performed by a device or profile owner, the install
14335                // reason should be enterprise policy.
14336                return PackageManager.INSTALL_REASON_POLICY;
14337            }
14338        }
14339
14340        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14341            // If the install is being performed by a regular app (i.e. neither system app nor
14342            // device or profile owner), we have no reason to believe that the app is acting on
14343            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14344            // change it to unknown instead.
14345            return PackageManager.INSTALL_REASON_UNKNOWN;
14346        }
14347
14348        // If the install is being performed by a regular app and the install reason was set to any
14349        // value but enterprise policy, leave the install reason unchanged.
14350        return installReason;
14351    }
14352
14353    void installStage(String packageName, File stagedDir, String stagedCid,
14354            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14355            String installerPackageName, int installerUid, UserHandle user,
14356            Certificate[][] certificates) {
14357        if (DEBUG_EPHEMERAL) {
14358            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14359                Slog.d(TAG, "Ephemeral install of " + packageName);
14360            }
14361        }
14362        final VerificationInfo verificationInfo = new VerificationInfo(
14363                sessionParams.originatingUri, sessionParams.referrerUri,
14364                sessionParams.originatingUid, installerUid);
14365
14366        final OriginInfo origin;
14367        if (stagedDir != null) {
14368            origin = OriginInfo.fromStagedFile(stagedDir);
14369        } else {
14370            origin = OriginInfo.fromStagedContainer(stagedCid);
14371        }
14372
14373        final Message msg = mHandler.obtainMessage(INIT_COPY);
14374        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14375                sessionParams.installReason);
14376        final InstallParams params = new InstallParams(origin, null, observer,
14377                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14378                verificationInfo, user, sessionParams.abiOverride,
14379                sessionParams.grantedRuntimePermissions, certificates, installReason);
14380        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14381        msg.obj = params;
14382
14383        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14384                System.identityHashCode(msg.obj));
14385        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14386                System.identityHashCode(msg.obj));
14387
14388        mHandler.sendMessage(msg);
14389    }
14390
14391    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14392            int userId) {
14393        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14394        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14395
14396        // Send a session commit broadcast
14397        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14398        info.installReason = pkgSetting.getInstallReason(userId);
14399        info.appPackageName = packageName;
14400        sendSessionCommitBroadcast(info, userId);
14401    }
14402
14403    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14404        if (ArrayUtils.isEmpty(userIds)) {
14405            return;
14406        }
14407        Bundle extras = new Bundle(1);
14408        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14409        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14410
14411        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14412                packageName, extras, 0, null, null, userIds);
14413        if (isSystem) {
14414            mHandler.post(() -> {
14415                        for (int userId : userIds) {
14416                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14417                        }
14418                    }
14419            );
14420        }
14421    }
14422
14423    /**
14424     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14425     * automatically without needing an explicit launch.
14426     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14427     */
14428    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14429        // If user is not running, the app didn't miss any broadcast
14430        if (!mUserManagerInternal.isUserRunning(userId)) {
14431            return;
14432        }
14433        final IActivityManager am = ActivityManager.getService();
14434        try {
14435            // Deliver LOCKED_BOOT_COMPLETED first
14436            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14437                    .setPackage(packageName);
14438            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14439            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14440                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14441
14442            // Deliver BOOT_COMPLETED only if user is unlocked
14443            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14444                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14445                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14446                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14447            }
14448        } catch (RemoteException e) {
14449            throw e.rethrowFromSystemServer();
14450        }
14451    }
14452
14453    @Override
14454    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14455            int userId) {
14456        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14457        PackageSetting pkgSetting;
14458        final int callingUid = Binder.getCallingUid();
14459        enforceCrossUserPermission(callingUid, userId,
14460                true /* requireFullPermission */, true /* checkShell */,
14461                "setApplicationHiddenSetting for user " + userId);
14462
14463        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14464            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14465            return false;
14466        }
14467
14468        long callingId = Binder.clearCallingIdentity();
14469        try {
14470            boolean sendAdded = false;
14471            boolean sendRemoved = false;
14472            // writer
14473            synchronized (mPackages) {
14474                pkgSetting = mSettings.mPackages.get(packageName);
14475                if (pkgSetting == null) {
14476                    return false;
14477                }
14478                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14479                    return false;
14480                }
14481                // Do not allow "android" is being disabled
14482                if ("android".equals(packageName)) {
14483                    Slog.w(TAG, "Cannot hide package: android");
14484                    return false;
14485                }
14486                // Cannot hide static shared libs as they are considered
14487                // a part of the using app (emulating static linking). Also
14488                // static libs are installed always on internal storage.
14489                PackageParser.Package pkg = mPackages.get(packageName);
14490                if (pkg != null && pkg.staticSharedLibName != null) {
14491                    Slog.w(TAG, "Cannot hide package: " + packageName
14492                            + " providing static shared library: "
14493                            + pkg.staticSharedLibName);
14494                    return false;
14495                }
14496                // Only allow protected packages to hide themselves.
14497                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14498                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14499                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14500                    return false;
14501                }
14502
14503                if (pkgSetting.getHidden(userId) != hidden) {
14504                    pkgSetting.setHidden(hidden, userId);
14505                    mSettings.writePackageRestrictionsLPr(userId);
14506                    if (hidden) {
14507                        sendRemoved = true;
14508                    } else {
14509                        sendAdded = true;
14510                    }
14511                }
14512            }
14513            if (sendAdded) {
14514                sendPackageAddedForUser(packageName, pkgSetting, userId);
14515                return true;
14516            }
14517            if (sendRemoved) {
14518                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14519                        "hiding pkg");
14520                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14521                return true;
14522            }
14523        } finally {
14524            Binder.restoreCallingIdentity(callingId);
14525        }
14526        return false;
14527    }
14528
14529    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14530            int userId) {
14531        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14532        info.removedPackage = packageName;
14533        info.installerPackageName = pkgSetting.installerPackageName;
14534        info.removedUsers = new int[] {userId};
14535        info.broadcastUsers = new int[] {userId};
14536        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14537        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14538    }
14539
14540    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14541        if (pkgList.length > 0) {
14542            Bundle extras = new Bundle(1);
14543            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14544
14545            sendPackageBroadcast(
14546                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14547                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14548                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14549                    new int[] {userId});
14550        }
14551    }
14552
14553    /**
14554     * Returns true if application is not found or there was an error. Otherwise it returns
14555     * the hidden state of the package for the given user.
14556     */
14557    @Override
14558    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14559        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14560        final int callingUid = Binder.getCallingUid();
14561        enforceCrossUserPermission(callingUid, userId,
14562                true /* requireFullPermission */, false /* checkShell */,
14563                "getApplicationHidden for user " + userId);
14564        PackageSetting ps;
14565        long callingId = Binder.clearCallingIdentity();
14566        try {
14567            // writer
14568            synchronized (mPackages) {
14569                ps = mSettings.mPackages.get(packageName);
14570                if (ps == null) {
14571                    return true;
14572                }
14573                if (filterAppAccessLPr(ps, callingUid, userId)) {
14574                    return true;
14575                }
14576                return ps.getHidden(userId);
14577            }
14578        } finally {
14579            Binder.restoreCallingIdentity(callingId);
14580        }
14581    }
14582
14583    /**
14584     * @hide
14585     */
14586    @Override
14587    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14588            int installReason) {
14589        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14590                null);
14591        PackageSetting pkgSetting;
14592        final int callingUid = Binder.getCallingUid();
14593        enforceCrossUserPermission(callingUid, userId,
14594                true /* requireFullPermission */, true /* checkShell */,
14595                "installExistingPackage for user " + userId);
14596        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14597            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14598        }
14599
14600        long callingId = Binder.clearCallingIdentity();
14601        try {
14602            boolean installed = false;
14603            final boolean instantApp =
14604                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14605            final boolean fullApp =
14606                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14607
14608            // writer
14609            synchronized (mPackages) {
14610                pkgSetting = mSettings.mPackages.get(packageName);
14611                if (pkgSetting == null) {
14612                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14613                }
14614                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14615                    // only allow the existing package to be used if it's installed as a full
14616                    // application for at least one user
14617                    boolean installAllowed = false;
14618                    for (int checkUserId : sUserManager.getUserIds()) {
14619                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14620                        if (installAllowed) {
14621                            break;
14622                        }
14623                    }
14624                    if (!installAllowed) {
14625                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14626                    }
14627                }
14628                if (!pkgSetting.getInstalled(userId)) {
14629                    pkgSetting.setInstalled(true, userId);
14630                    pkgSetting.setHidden(false, userId);
14631                    pkgSetting.setInstallReason(installReason, userId);
14632                    mSettings.writePackageRestrictionsLPr(userId);
14633                    mSettings.writeKernelMappingLPr(pkgSetting);
14634                    installed = true;
14635                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14636                    // upgrade app from instant to full; we don't allow app downgrade
14637                    installed = true;
14638                }
14639                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14640            }
14641
14642            if (installed) {
14643                if (pkgSetting.pkg != null) {
14644                    synchronized (mInstallLock) {
14645                        // We don't need to freeze for a brand new install
14646                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14647                    }
14648                }
14649                sendPackageAddedForUser(packageName, pkgSetting, userId);
14650                synchronized (mPackages) {
14651                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14652                }
14653            }
14654        } finally {
14655            Binder.restoreCallingIdentity(callingId);
14656        }
14657
14658        return PackageManager.INSTALL_SUCCEEDED;
14659    }
14660
14661    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14662            boolean instantApp, boolean fullApp) {
14663        // no state specified; do nothing
14664        if (!instantApp && !fullApp) {
14665            return;
14666        }
14667        if (userId != UserHandle.USER_ALL) {
14668            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14669                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14670            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14671                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14672            }
14673        } else {
14674            for (int currentUserId : sUserManager.getUserIds()) {
14675                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14676                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14677                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14678                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14679                }
14680            }
14681        }
14682    }
14683
14684    boolean isUserRestricted(int userId, String restrictionKey) {
14685        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14686        if (restrictions.getBoolean(restrictionKey, false)) {
14687            Log.w(TAG, "User is restricted: " + restrictionKey);
14688            return true;
14689        }
14690        return false;
14691    }
14692
14693    @Override
14694    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14695            int userId) {
14696        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14697        final int callingUid = Binder.getCallingUid();
14698        enforceCrossUserPermission(callingUid, userId,
14699                true /* requireFullPermission */, true /* checkShell */,
14700                "setPackagesSuspended for user " + userId);
14701
14702        if (ArrayUtils.isEmpty(packageNames)) {
14703            return packageNames;
14704        }
14705
14706        // List of package names for whom the suspended state has changed.
14707        List<String> changedPackages = new ArrayList<>(packageNames.length);
14708        // List of package names for whom the suspended state is not set as requested in this
14709        // method.
14710        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14711        long callingId = Binder.clearCallingIdentity();
14712        try {
14713            for (int i = 0; i < packageNames.length; i++) {
14714                String packageName = packageNames[i];
14715                boolean changed = false;
14716                final int appId;
14717                synchronized (mPackages) {
14718                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14719                    if (pkgSetting == null
14720                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14721                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14722                                + "\". Skipping suspending/un-suspending.");
14723                        unactionedPackages.add(packageName);
14724                        continue;
14725                    }
14726                    appId = pkgSetting.appId;
14727                    if (pkgSetting.getSuspended(userId) != suspended) {
14728                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14729                            unactionedPackages.add(packageName);
14730                            continue;
14731                        }
14732                        pkgSetting.setSuspended(suspended, userId);
14733                        mSettings.writePackageRestrictionsLPr(userId);
14734                        changed = true;
14735                        changedPackages.add(packageName);
14736                    }
14737                }
14738
14739                if (changed && suspended) {
14740                    killApplication(packageName, UserHandle.getUid(userId, appId),
14741                            "suspending package");
14742                }
14743            }
14744        } finally {
14745            Binder.restoreCallingIdentity(callingId);
14746        }
14747
14748        if (!changedPackages.isEmpty()) {
14749            sendPackagesSuspendedForUser(changedPackages.toArray(
14750                    new String[changedPackages.size()]), userId, suspended);
14751        }
14752
14753        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14754    }
14755
14756    @Override
14757    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14758        final int callingUid = Binder.getCallingUid();
14759        enforceCrossUserPermission(callingUid, userId,
14760                true /* requireFullPermission */, false /* checkShell */,
14761                "isPackageSuspendedForUser for user " + userId);
14762        synchronized (mPackages) {
14763            final PackageSetting ps = mSettings.mPackages.get(packageName);
14764            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14765                throw new IllegalArgumentException("Unknown target package: " + packageName);
14766            }
14767            return ps.getSuspended(userId);
14768        }
14769    }
14770
14771    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14772        if (isPackageDeviceAdmin(packageName, userId)) {
14773            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14774                    + "\": has an active device admin");
14775            return false;
14776        }
14777
14778        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14779        if (packageName.equals(activeLauncherPackageName)) {
14780            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14781                    + "\": contains the active launcher");
14782            return false;
14783        }
14784
14785        if (packageName.equals(mRequiredInstallerPackage)) {
14786            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14787                    + "\": required for package installation");
14788            return false;
14789        }
14790
14791        if (packageName.equals(mRequiredUninstallerPackage)) {
14792            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14793                    + "\": required for package uninstallation");
14794            return false;
14795        }
14796
14797        if (packageName.equals(mRequiredVerifierPackage)) {
14798            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14799                    + "\": required for package verification");
14800            return false;
14801        }
14802
14803        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14804            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14805                    + "\": is the default dialer");
14806            return false;
14807        }
14808
14809        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14810            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14811                    + "\": protected package");
14812            return false;
14813        }
14814
14815        // Cannot suspend static shared libs as they are considered
14816        // a part of the using app (emulating static linking). Also
14817        // static libs are installed always on internal storage.
14818        PackageParser.Package pkg = mPackages.get(packageName);
14819        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14820            Slog.w(TAG, "Cannot suspend package: " + packageName
14821                    + " providing static shared library: "
14822                    + pkg.staticSharedLibName);
14823            return false;
14824        }
14825
14826        return true;
14827    }
14828
14829    private String getActiveLauncherPackageName(int userId) {
14830        Intent intent = new Intent(Intent.ACTION_MAIN);
14831        intent.addCategory(Intent.CATEGORY_HOME);
14832        ResolveInfo resolveInfo = resolveIntent(
14833                intent,
14834                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14835                PackageManager.MATCH_DEFAULT_ONLY,
14836                userId);
14837
14838        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14839    }
14840
14841    private String getDefaultDialerPackageName(int userId) {
14842        synchronized (mPackages) {
14843            return mSettings.getDefaultDialerPackageNameLPw(userId);
14844        }
14845    }
14846
14847    @Override
14848    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14849        mContext.enforceCallingOrSelfPermission(
14850                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14851                "Only package verification agents can verify applications");
14852
14853        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14854        final PackageVerificationResponse response = new PackageVerificationResponse(
14855                verificationCode, Binder.getCallingUid());
14856        msg.arg1 = id;
14857        msg.obj = response;
14858        mHandler.sendMessage(msg);
14859    }
14860
14861    @Override
14862    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14863            long millisecondsToDelay) {
14864        mContext.enforceCallingOrSelfPermission(
14865                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14866                "Only package verification agents can extend verification timeouts");
14867
14868        final PackageVerificationState state = mPendingVerification.get(id);
14869        final PackageVerificationResponse response = new PackageVerificationResponse(
14870                verificationCodeAtTimeout, Binder.getCallingUid());
14871
14872        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14873            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14874        }
14875        if (millisecondsToDelay < 0) {
14876            millisecondsToDelay = 0;
14877        }
14878        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14879                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14880            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14881        }
14882
14883        if ((state != null) && !state.timeoutExtended()) {
14884            state.extendTimeout();
14885
14886            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14887            msg.arg1 = id;
14888            msg.obj = response;
14889            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14890        }
14891    }
14892
14893    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14894            int verificationCode, UserHandle user) {
14895        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14896        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14897        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14898        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14899        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14900
14901        mContext.sendBroadcastAsUser(intent, user,
14902                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14903    }
14904
14905    private ComponentName matchComponentForVerifier(String packageName,
14906            List<ResolveInfo> receivers) {
14907        ActivityInfo targetReceiver = null;
14908
14909        final int NR = receivers.size();
14910        for (int i = 0; i < NR; i++) {
14911            final ResolveInfo info = receivers.get(i);
14912            if (info.activityInfo == null) {
14913                continue;
14914            }
14915
14916            if (packageName.equals(info.activityInfo.packageName)) {
14917                targetReceiver = info.activityInfo;
14918                break;
14919            }
14920        }
14921
14922        if (targetReceiver == null) {
14923            return null;
14924        }
14925
14926        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14927    }
14928
14929    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14930            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14931        if (pkgInfo.verifiers.length == 0) {
14932            return null;
14933        }
14934
14935        final int N = pkgInfo.verifiers.length;
14936        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14937        for (int i = 0; i < N; i++) {
14938            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14939
14940            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14941                    receivers);
14942            if (comp == null) {
14943                continue;
14944            }
14945
14946            final int verifierUid = getUidForVerifier(verifierInfo);
14947            if (verifierUid == -1) {
14948                continue;
14949            }
14950
14951            if (DEBUG_VERIFY) {
14952                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14953                        + " with the correct signature");
14954            }
14955            sufficientVerifiers.add(comp);
14956            verificationState.addSufficientVerifier(verifierUid);
14957        }
14958
14959        return sufficientVerifiers;
14960    }
14961
14962    private int getUidForVerifier(VerifierInfo verifierInfo) {
14963        synchronized (mPackages) {
14964            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14965            if (pkg == null) {
14966                return -1;
14967            } else if (pkg.mSignatures.length != 1) {
14968                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14969                        + " has more than one signature; ignoring");
14970                return -1;
14971            }
14972
14973            /*
14974             * If the public key of the package's signature does not match
14975             * our expected public key, then this is a different package and
14976             * we should skip.
14977             */
14978
14979            final byte[] expectedPublicKey;
14980            try {
14981                final Signature verifierSig = pkg.mSignatures[0];
14982                final PublicKey publicKey = verifierSig.getPublicKey();
14983                expectedPublicKey = publicKey.getEncoded();
14984            } catch (CertificateException e) {
14985                return -1;
14986            }
14987
14988            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14989
14990            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14991                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14992                        + " does not have the expected public key; ignoring");
14993                return -1;
14994            }
14995
14996            return pkg.applicationInfo.uid;
14997        }
14998    }
14999
15000    @Override
15001    public void finishPackageInstall(int token, boolean didLaunch) {
15002        enforceSystemOrRoot("Only the system is allowed to finish installs");
15003
15004        if (DEBUG_INSTALL) {
15005            Slog.v(TAG, "BM finishing package install for " + token);
15006        }
15007        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15008
15009        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15010        mHandler.sendMessage(msg);
15011    }
15012
15013    /**
15014     * Get the verification agent timeout.  Used for both the APK verifier and the
15015     * intent filter verifier.
15016     *
15017     * @return verification timeout in milliseconds
15018     */
15019    private long getVerificationTimeout() {
15020        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15021                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15022                DEFAULT_VERIFICATION_TIMEOUT);
15023    }
15024
15025    /**
15026     * Get the default verification agent response code.
15027     *
15028     * @return default verification response code
15029     */
15030    private int getDefaultVerificationResponse(UserHandle user) {
15031        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15032            return PackageManager.VERIFICATION_REJECT;
15033        }
15034        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15035                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15036                DEFAULT_VERIFICATION_RESPONSE);
15037    }
15038
15039    /**
15040     * Check whether or not package verification has been enabled.
15041     *
15042     * @return true if verification should be performed
15043     */
15044    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15045        if (!DEFAULT_VERIFY_ENABLE) {
15046            return false;
15047        }
15048
15049        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15050
15051        // Check if installing from ADB
15052        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15053            // Do not run verification in a test harness environment
15054            if (ActivityManager.isRunningInTestHarness()) {
15055                return false;
15056            }
15057            if (ensureVerifyAppsEnabled) {
15058                return true;
15059            }
15060            // Check if the developer does not want package verification for ADB installs
15061            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15062                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15063                return false;
15064            }
15065        } else {
15066            // only when not installed from ADB, skip verification for instant apps when
15067            // the installer and verifier are the same.
15068            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15069                if (mInstantAppInstallerActivity != null
15070                        && mInstantAppInstallerActivity.packageName.equals(
15071                                mRequiredVerifierPackage)) {
15072                    try {
15073                        mContext.getSystemService(AppOpsManager.class)
15074                                .checkPackage(installerUid, mRequiredVerifierPackage);
15075                        if (DEBUG_VERIFY) {
15076                            Slog.i(TAG, "disable verification for instant app");
15077                        }
15078                        return false;
15079                    } catch (SecurityException ignore) { }
15080                }
15081            }
15082        }
15083
15084        if (ensureVerifyAppsEnabled) {
15085            return true;
15086        }
15087
15088        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15089                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15090    }
15091
15092    @Override
15093    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15094            throws RemoteException {
15095        mContext.enforceCallingOrSelfPermission(
15096                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15097                "Only intentfilter verification agents can verify applications");
15098
15099        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15100        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15101                Binder.getCallingUid(), verificationCode, failedDomains);
15102        msg.arg1 = id;
15103        msg.obj = response;
15104        mHandler.sendMessage(msg);
15105    }
15106
15107    @Override
15108    public int getIntentVerificationStatus(String packageName, int userId) {
15109        final int callingUid = Binder.getCallingUid();
15110        if (getInstantAppPackageName(callingUid) != null) {
15111            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15112        }
15113        synchronized (mPackages) {
15114            final PackageSetting ps = mSettings.mPackages.get(packageName);
15115            if (ps == null
15116                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15117                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15118            }
15119            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15120        }
15121    }
15122
15123    @Override
15124    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15125        mContext.enforceCallingOrSelfPermission(
15126                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15127
15128        boolean result = false;
15129        synchronized (mPackages) {
15130            final PackageSetting ps = mSettings.mPackages.get(packageName);
15131            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15132                return false;
15133            }
15134            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15135        }
15136        if (result) {
15137            scheduleWritePackageRestrictionsLocked(userId);
15138        }
15139        return result;
15140    }
15141
15142    @Override
15143    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15144            String packageName) {
15145        final int callingUid = Binder.getCallingUid();
15146        if (getInstantAppPackageName(callingUid) != null) {
15147            return ParceledListSlice.emptyList();
15148        }
15149        synchronized (mPackages) {
15150            final PackageSetting ps = mSettings.mPackages.get(packageName);
15151            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15152                return ParceledListSlice.emptyList();
15153            }
15154            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15155        }
15156    }
15157
15158    @Override
15159    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15160        if (TextUtils.isEmpty(packageName)) {
15161            return ParceledListSlice.emptyList();
15162        }
15163        final int callingUid = Binder.getCallingUid();
15164        final int callingUserId = UserHandle.getUserId(callingUid);
15165        synchronized (mPackages) {
15166            PackageParser.Package pkg = mPackages.get(packageName);
15167            if (pkg == null || pkg.activities == null) {
15168                return ParceledListSlice.emptyList();
15169            }
15170            if (pkg.mExtras == null) {
15171                return ParceledListSlice.emptyList();
15172            }
15173            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15174            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15175                return ParceledListSlice.emptyList();
15176            }
15177            final int count = pkg.activities.size();
15178            ArrayList<IntentFilter> result = new ArrayList<>();
15179            for (int n=0; n<count; n++) {
15180                PackageParser.Activity activity = pkg.activities.get(n);
15181                if (activity.intents != null && activity.intents.size() > 0) {
15182                    result.addAll(activity.intents);
15183                }
15184            }
15185            return new ParceledListSlice<>(result);
15186        }
15187    }
15188
15189    @Override
15190    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15191        mContext.enforceCallingOrSelfPermission(
15192                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15193
15194        synchronized (mPackages) {
15195            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15196            if (packageName != null) {
15197                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15198                        packageName, userId);
15199            }
15200            return result;
15201        }
15202    }
15203
15204    @Override
15205    public String getDefaultBrowserPackageName(int userId) {
15206        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15207            return null;
15208        }
15209        synchronized (mPackages) {
15210            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15211        }
15212    }
15213
15214    /**
15215     * Get the "allow unknown sources" setting.
15216     *
15217     * @return the current "allow unknown sources" setting
15218     */
15219    private int getUnknownSourcesSettings() {
15220        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15221                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15222                -1);
15223    }
15224
15225    @Override
15226    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15227        final int callingUid = Binder.getCallingUid();
15228        if (getInstantAppPackageName(callingUid) != null) {
15229            return;
15230        }
15231        // writer
15232        synchronized (mPackages) {
15233            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15234            if (targetPackageSetting == null
15235                    || filterAppAccessLPr(
15236                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15237                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15238            }
15239
15240            PackageSetting installerPackageSetting;
15241            if (installerPackageName != null) {
15242                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15243                if (installerPackageSetting == null) {
15244                    throw new IllegalArgumentException("Unknown installer package: "
15245                            + installerPackageName);
15246                }
15247            } else {
15248                installerPackageSetting = null;
15249            }
15250
15251            Signature[] callerSignature;
15252            Object obj = mSettings.getUserIdLPr(callingUid);
15253            if (obj != null) {
15254                if (obj instanceof SharedUserSetting) {
15255                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15256                } else if (obj instanceof PackageSetting) {
15257                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15258                } else {
15259                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15260                }
15261            } else {
15262                throw new SecurityException("Unknown calling UID: " + callingUid);
15263            }
15264
15265            // Verify: can't set installerPackageName to a package that is
15266            // not signed with the same cert as the caller.
15267            if (installerPackageSetting != null) {
15268                if (compareSignatures(callerSignature,
15269                        installerPackageSetting.signatures.mSignatures)
15270                        != PackageManager.SIGNATURE_MATCH) {
15271                    throw new SecurityException(
15272                            "Caller does not have same cert as new installer package "
15273                            + installerPackageName);
15274                }
15275            }
15276
15277            // Verify: if target already has an installer package, it must
15278            // be signed with the same cert as the caller.
15279            if (targetPackageSetting.installerPackageName != null) {
15280                PackageSetting setting = mSettings.mPackages.get(
15281                        targetPackageSetting.installerPackageName);
15282                // If the currently set package isn't valid, then it's always
15283                // okay to change it.
15284                if (setting != null) {
15285                    if (compareSignatures(callerSignature,
15286                            setting.signatures.mSignatures)
15287                            != PackageManager.SIGNATURE_MATCH) {
15288                        throw new SecurityException(
15289                                "Caller does not have same cert as old installer package "
15290                                + targetPackageSetting.installerPackageName);
15291                    }
15292                }
15293            }
15294
15295            // Okay!
15296            targetPackageSetting.installerPackageName = installerPackageName;
15297            if (installerPackageName != null) {
15298                mSettings.mInstallerPackages.add(installerPackageName);
15299            }
15300            scheduleWriteSettingsLocked();
15301        }
15302    }
15303
15304    @Override
15305    public void setApplicationCategoryHint(String packageName, int categoryHint,
15306            String callerPackageName) {
15307        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15308            throw new SecurityException("Instant applications don't have access to this method");
15309        }
15310        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15311                callerPackageName);
15312        synchronized (mPackages) {
15313            PackageSetting ps = mSettings.mPackages.get(packageName);
15314            if (ps == null) {
15315                throw new IllegalArgumentException("Unknown target package " + packageName);
15316            }
15317            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15318                throw new IllegalArgumentException("Unknown target package " + packageName);
15319            }
15320            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15321                throw new IllegalArgumentException("Calling package " + callerPackageName
15322                        + " is not installer for " + packageName);
15323            }
15324
15325            if (ps.categoryHint != categoryHint) {
15326                ps.categoryHint = categoryHint;
15327                scheduleWriteSettingsLocked();
15328            }
15329        }
15330    }
15331
15332    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15333        // Queue up an async operation since the package installation may take a little while.
15334        mHandler.post(new Runnable() {
15335            public void run() {
15336                mHandler.removeCallbacks(this);
15337                 // Result object to be returned
15338                PackageInstalledInfo res = new PackageInstalledInfo();
15339                res.setReturnCode(currentStatus);
15340                res.uid = -1;
15341                res.pkg = null;
15342                res.removedInfo = null;
15343                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15344                    args.doPreInstall(res.returnCode);
15345                    synchronized (mInstallLock) {
15346                        installPackageTracedLI(args, res);
15347                    }
15348                    args.doPostInstall(res.returnCode, res.uid);
15349                }
15350
15351                // A restore should be performed at this point if (a) the install
15352                // succeeded, (b) the operation is not an update, and (c) the new
15353                // package has not opted out of backup participation.
15354                final boolean update = res.removedInfo != null
15355                        && res.removedInfo.removedPackage != null;
15356                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15357                boolean doRestore = !update
15358                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15359
15360                // Set up the post-install work request bookkeeping.  This will be used
15361                // and cleaned up by the post-install event handling regardless of whether
15362                // there's a restore pass performed.  Token values are >= 1.
15363                int token;
15364                if (mNextInstallToken < 0) mNextInstallToken = 1;
15365                token = mNextInstallToken++;
15366
15367                PostInstallData data = new PostInstallData(args, res);
15368                mRunningInstalls.put(token, data);
15369                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15370
15371                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15372                    // Pass responsibility to the Backup Manager.  It will perform a
15373                    // restore if appropriate, then pass responsibility back to the
15374                    // Package Manager to run the post-install observer callbacks
15375                    // and broadcasts.
15376                    IBackupManager bm = IBackupManager.Stub.asInterface(
15377                            ServiceManager.getService(Context.BACKUP_SERVICE));
15378                    if (bm != null) {
15379                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15380                                + " to BM for possible restore");
15381                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15382                        try {
15383                            // TODO: http://b/22388012
15384                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15385                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15386                            } else {
15387                                doRestore = false;
15388                            }
15389                        } catch (RemoteException e) {
15390                            // can't happen; the backup manager is local
15391                        } catch (Exception e) {
15392                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15393                            doRestore = false;
15394                        }
15395                    } else {
15396                        Slog.e(TAG, "Backup Manager not found!");
15397                        doRestore = false;
15398                    }
15399                }
15400
15401                if (!doRestore) {
15402                    // No restore possible, or the Backup Manager was mysteriously not
15403                    // available -- just fire the post-install work request directly.
15404                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15405
15406                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15407
15408                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15409                    mHandler.sendMessage(msg);
15410                }
15411            }
15412        });
15413    }
15414
15415    /**
15416     * Callback from PackageSettings whenever an app is first transitioned out of the
15417     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15418     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15419     * here whether the app is the target of an ongoing install, and only send the
15420     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15421     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15422     * handling.
15423     */
15424    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15425        // Serialize this with the rest of the install-process message chain.  In the
15426        // restore-at-install case, this Runnable will necessarily run before the
15427        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15428        // are coherent.  In the non-restore case, the app has already completed install
15429        // and been launched through some other means, so it is not in a problematic
15430        // state for observers to see the FIRST_LAUNCH signal.
15431        mHandler.post(new Runnable() {
15432            @Override
15433            public void run() {
15434                for (int i = 0; i < mRunningInstalls.size(); i++) {
15435                    final PostInstallData data = mRunningInstalls.valueAt(i);
15436                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15437                        continue;
15438                    }
15439                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15440                        // right package; but is it for the right user?
15441                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15442                            if (userId == data.res.newUsers[uIndex]) {
15443                                if (DEBUG_BACKUP) {
15444                                    Slog.i(TAG, "Package " + pkgName
15445                                            + " being restored so deferring FIRST_LAUNCH");
15446                                }
15447                                return;
15448                            }
15449                        }
15450                    }
15451                }
15452                // didn't find it, so not being restored
15453                if (DEBUG_BACKUP) {
15454                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15455                }
15456                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15457            }
15458        });
15459    }
15460
15461    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15462        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15463                installerPkg, null, userIds);
15464    }
15465
15466    private abstract class HandlerParams {
15467        private static final int MAX_RETRIES = 4;
15468
15469        /**
15470         * Number of times startCopy() has been attempted and had a non-fatal
15471         * error.
15472         */
15473        private int mRetries = 0;
15474
15475        /** User handle for the user requesting the information or installation. */
15476        private final UserHandle mUser;
15477        String traceMethod;
15478        int traceCookie;
15479
15480        HandlerParams(UserHandle user) {
15481            mUser = user;
15482        }
15483
15484        UserHandle getUser() {
15485            return mUser;
15486        }
15487
15488        HandlerParams setTraceMethod(String traceMethod) {
15489            this.traceMethod = traceMethod;
15490            return this;
15491        }
15492
15493        HandlerParams setTraceCookie(int traceCookie) {
15494            this.traceCookie = traceCookie;
15495            return this;
15496        }
15497
15498        final boolean startCopy() {
15499            boolean res;
15500            try {
15501                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15502
15503                if (++mRetries > MAX_RETRIES) {
15504                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15505                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15506                    handleServiceError();
15507                    return false;
15508                } else {
15509                    handleStartCopy();
15510                    res = true;
15511                }
15512            } catch (RemoteException e) {
15513                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15514                mHandler.sendEmptyMessage(MCS_RECONNECT);
15515                res = false;
15516            }
15517            handleReturnCode();
15518            return res;
15519        }
15520
15521        final void serviceError() {
15522            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15523            handleServiceError();
15524            handleReturnCode();
15525        }
15526
15527        abstract void handleStartCopy() throws RemoteException;
15528        abstract void handleServiceError();
15529        abstract void handleReturnCode();
15530    }
15531
15532    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15533        for (File path : paths) {
15534            try {
15535                mcs.clearDirectory(path.getAbsolutePath());
15536            } catch (RemoteException e) {
15537            }
15538        }
15539    }
15540
15541    static class OriginInfo {
15542        /**
15543         * Location where install is coming from, before it has been
15544         * copied/renamed into place. This could be a single monolithic APK
15545         * file, or a cluster directory. This location may be untrusted.
15546         */
15547        final File file;
15548        final String cid;
15549
15550        /**
15551         * Flag indicating that {@link #file} or {@link #cid} has already been
15552         * staged, meaning downstream users don't need to defensively copy the
15553         * contents.
15554         */
15555        final boolean staged;
15556
15557        /**
15558         * Flag indicating that {@link #file} or {@link #cid} is an already
15559         * installed app that is being moved.
15560         */
15561        final boolean existing;
15562
15563        final String resolvedPath;
15564        final File resolvedFile;
15565
15566        static OriginInfo fromNothing() {
15567            return new OriginInfo(null, null, false, false);
15568        }
15569
15570        static OriginInfo fromUntrustedFile(File file) {
15571            return new OriginInfo(file, null, false, false);
15572        }
15573
15574        static OriginInfo fromExistingFile(File file) {
15575            return new OriginInfo(file, null, false, true);
15576        }
15577
15578        static OriginInfo fromStagedFile(File file) {
15579            return new OriginInfo(file, null, true, false);
15580        }
15581
15582        static OriginInfo fromStagedContainer(String cid) {
15583            return new OriginInfo(null, cid, true, false);
15584        }
15585
15586        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15587            this.file = file;
15588            this.cid = cid;
15589            this.staged = staged;
15590            this.existing = existing;
15591
15592            if (cid != null) {
15593                resolvedPath = PackageHelper.getSdDir(cid);
15594                resolvedFile = new File(resolvedPath);
15595            } else if (file != null) {
15596                resolvedPath = file.getAbsolutePath();
15597                resolvedFile = file;
15598            } else {
15599                resolvedPath = null;
15600                resolvedFile = null;
15601            }
15602        }
15603    }
15604
15605    static class MoveInfo {
15606        final int moveId;
15607        final String fromUuid;
15608        final String toUuid;
15609        final String packageName;
15610        final String dataAppName;
15611        final int appId;
15612        final String seinfo;
15613        final int targetSdkVersion;
15614
15615        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15616                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15617            this.moveId = moveId;
15618            this.fromUuid = fromUuid;
15619            this.toUuid = toUuid;
15620            this.packageName = packageName;
15621            this.dataAppName = dataAppName;
15622            this.appId = appId;
15623            this.seinfo = seinfo;
15624            this.targetSdkVersion = targetSdkVersion;
15625        }
15626    }
15627
15628    static class VerificationInfo {
15629        /** A constant used to indicate that a uid value is not present. */
15630        public static final int NO_UID = -1;
15631
15632        /** URI referencing where the package was downloaded from. */
15633        final Uri originatingUri;
15634
15635        /** HTTP referrer URI associated with the originatingURI. */
15636        final Uri referrer;
15637
15638        /** UID of the application that the install request originated from. */
15639        final int originatingUid;
15640
15641        /** UID of application requesting the install */
15642        final int installerUid;
15643
15644        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15645            this.originatingUri = originatingUri;
15646            this.referrer = referrer;
15647            this.originatingUid = originatingUid;
15648            this.installerUid = installerUid;
15649        }
15650    }
15651
15652    class InstallParams extends HandlerParams {
15653        final OriginInfo origin;
15654        final MoveInfo move;
15655        final IPackageInstallObserver2 observer;
15656        int installFlags;
15657        final String installerPackageName;
15658        final String volumeUuid;
15659        private InstallArgs mArgs;
15660        private int mRet;
15661        final String packageAbiOverride;
15662        final String[] grantedRuntimePermissions;
15663        final VerificationInfo verificationInfo;
15664        final Certificate[][] certificates;
15665        final int installReason;
15666
15667        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15668                int installFlags, String installerPackageName, String volumeUuid,
15669                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15670                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15671            super(user);
15672            this.origin = origin;
15673            this.move = move;
15674            this.observer = observer;
15675            this.installFlags = installFlags;
15676            this.installerPackageName = installerPackageName;
15677            this.volumeUuid = volumeUuid;
15678            this.verificationInfo = verificationInfo;
15679            this.packageAbiOverride = packageAbiOverride;
15680            this.grantedRuntimePermissions = grantedPermissions;
15681            this.certificates = certificates;
15682            this.installReason = installReason;
15683        }
15684
15685        @Override
15686        public String toString() {
15687            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15688                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15689        }
15690
15691        private int installLocationPolicy(PackageInfoLite pkgLite) {
15692            String packageName = pkgLite.packageName;
15693            int installLocation = pkgLite.installLocation;
15694            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15695            // reader
15696            synchronized (mPackages) {
15697                // Currently installed package which the new package is attempting to replace or
15698                // null if no such package is installed.
15699                PackageParser.Package installedPkg = mPackages.get(packageName);
15700                // Package which currently owns the data which the new package will own if installed.
15701                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15702                // will be null whereas dataOwnerPkg will contain information about the package
15703                // which was uninstalled while keeping its data.
15704                PackageParser.Package dataOwnerPkg = installedPkg;
15705                if (dataOwnerPkg  == null) {
15706                    PackageSetting ps = mSettings.mPackages.get(packageName);
15707                    if (ps != null) {
15708                        dataOwnerPkg = ps.pkg;
15709                    }
15710                }
15711
15712                if (dataOwnerPkg != null) {
15713                    // If installed, the package will get access to data left on the device by its
15714                    // predecessor. As a security measure, this is permited only if this is not a
15715                    // version downgrade or if the predecessor package is marked as debuggable and
15716                    // a downgrade is explicitly requested.
15717                    //
15718                    // On debuggable platform builds, downgrades are permitted even for
15719                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15720                    // not offer security guarantees and thus it's OK to disable some security
15721                    // mechanisms to make debugging/testing easier on those builds. However, even on
15722                    // debuggable builds downgrades of packages are permitted only if requested via
15723                    // installFlags. This is because we aim to keep the behavior of debuggable
15724                    // platform builds as close as possible to the behavior of non-debuggable
15725                    // platform builds.
15726                    final boolean downgradeRequested =
15727                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15728                    final boolean packageDebuggable =
15729                                (dataOwnerPkg.applicationInfo.flags
15730                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15731                    final boolean downgradePermitted =
15732                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15733                    if (!downgradePermitted) {
15734                        try {
15735                            checkDowngrade(dataOwnerPkg, pkgLite);
15736                        } catch (PackageManagerException e) {
15737                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15738                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15739                        }
15740                    }
15741                }
15742
15743                if (installedPkg != null) {
15744                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15745                        // Check for updated system application.
15746                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15747                            if (onSd) {
15748                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15749                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15750                            }
15751                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15752                        } else {
15753                            if (onSd) {
15754                                // Install flag overrides everything.
15755                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15756                            }
15757                            // If current upgrade specifies particular preference
15758                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15759                                // Application explicitly specified internal.
15760                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15761                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15762                                // App explictly prefers external. Let policy decide
15763                            } else {
15764                                // Prefer previous location
15765                                if (isExternal(installedPkg)) {
15766                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15767                                }
15768                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15769                            }
15770                        }
15771                    } else {
15772                        // Invalid install. Return error code
15773                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15774                    }
15775                }
15776            }
15777            // All the special cases have been taken care of.
15778            // Return result based on recommended install location.
15779            if (onSd) {
15780                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15781            }
15782            return pkgLite.recommendedInstallLocation;
15783        }
15784
15785        /*
15786         * Invoke remote method to get package information and install
15787         * location values. Override install location based on default
15788         * policy if needed and then create install arguments based
15789         * on the install location.
15790         */
15791        public void handleStartCopy() throws RemoteException {
15792            int ret = PackageManager.INSTALL_SUCCEEDED;
15793
15794            // If we're already staged, we've firmly committed to an install location
15795            if (origin.staged) {
15796                if (origin.file != null) {
15797                    installFlags |= PackageManager.INSTALL_INTERNAL;
15798                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15799                } else if (origin.cid != null) {
15800                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15801                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15802                } else {
15803                    throw new IllegalStateException("Invalid stage location");
15804                }
15805            }
15806
15807            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15808            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15809            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15810            PackageInfoLite pkgLite = null;
15811
15812            if (onInt && onSd) {
15813                // Check if both bits are set.
15814                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15815                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15816            } else if (onSd && ephemeral) {
15817                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15818                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15819            } else {
15820                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15821                        packageAbiOverride);
15822
15823                if (DEBUG_EPHEMERAL && ephemeral) {
15824                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15825                }
15826
15827                /*
15828                 * If we have too little free space, try to free cache
15829                 * before giving up.
15830                 */
15831                if (!origin.staged && pkgLite.recommendedInstallLocation
15832                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15833                    // TODO: focus freeing disk space on the target device
15834                    final StorageManager storage = StorageManager.from(mContext);
15835                    final long lowThreshold = storage.getStorageLowBytes(
15836                            Environment.getDataDirectory());
15837
15838                    final long sizeBytes = mContainerService.calculateInstalledSize(
15839                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15840
15841                    try {
15842                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15843                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15844                                installFlags, packageAbiOverride);
15845                    } catch (InstallerException e) {
15846                        Slog.w(TAG, "Failed to free cache", e);
15847                    }
15848
15849                    /*
15850                     * The cache free must have deleted the file we
15851                     * downloaded to install.
15852                     *
15853                     * TODO: fix the "freeCache" call to not delete
15854                     *       the file we care about.
15855                     */
15856                    if (pkgLite.recommendedInstallLocation
15857                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15858                        pkgLite.recommendedInstallLocation
15859                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15860                    }
15861                }
15862            }
15863
15864            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15865                int loc = pkgLite.recommendedInstallLocation;
15866                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15867                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15868                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15869                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15870                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15871                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15872                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15873                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15874                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15875                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15876                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15877                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15878                } else {
15879                    // Override with defaults if needed.
15880                    loc = installLocationPolicy(pkgLite);
15881                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15882                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15883                    } else if (!onSd && !onInt) {
15884                        // Override install location with flags
15885                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15886                            // Set the flag to install on external media.
15887                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15888                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15889                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15890                            if (DEBUG_EPHEMERAL) {
15891                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15892                            }
15893                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15894                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15895                                    |PackageManager.INSTALL_INTERNAL);
15896                        } else {
15897                            // Make sure the flag for installing on external
15898                            // media is unset
15899                            installFlags |= PackageManager.INSTALL_INTERNAL;
15900                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15901                        }
15902                    }
15903                }
15904            }
15905
15906            final InstallArgs args = createInstallArgs(this);
15907            mArgs = args;
15908
15909            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15910                // TODO: http://b/22976637
15911                // Apps installed for "all" users use the device owner to verify the app
15912                UserHandle verifierUser = getUser();
15913                if (verifierUser == UserHandle.ALL) {
15914                    verifierUser = UserHandle.SYSTEM;
15915                }
15916
15917                /*
15918                 * Determine if we have any installed package verifiers. If we
15919                 * do, then we'll defer to them to verify the packages.
15920                 */
15921                final int requiredUid = mRequiredVerifierPackage == null ? -1
15922                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15923                                verifierUser.getIdentifier());
15924                final int installerUid =
15925                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15926                if (!origin.existing && requiredUid != -1
15927                        && isVerificationEnabled(
15928                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15929                    final Intent verification = new Intent(
15930                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15931                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15932                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15933                            PACKAGE_MIME_TYPE);
15934                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15935
15936                    // Query all live verifiers based on current user state
15937                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15938                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15939
15940                    if (DEBUG_VERIFY) {
15941                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15942                                + verification.toString() + " with " + pkgLite.verifiers.length
15943                                + " optional verifiers");
15944                    }
15945
15946                    final int verificationId = mPendingVerificationToken++;
15947
15948                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15949
15950                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15951                            installerPackageName);
15952
15953                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15954                            installFlags);
15955
15956                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15957                            pkgLite.packageName);
15958
15959                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15960                            pkgLite.versionCode);
15961
15962                    if (verificationInfo != null) {
15963                        if (verificationInfo.originatingUri != null) {
15964                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15965                                    verificationInfo.originatingUri);
15966                        }
15967                        if (verificationInfo.referrer != null) {
15968                            verification.putExtra(Intent.EXTRA_REFERRER,
15969                                    verificationInfo.referrer);
15970                        }
15971                        if (verificationInfo.originatingUid >= 0) {
15972                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15973                                    verificationInfo.originatingUid);
15974                        }
15975                        if (verificationInfo.installerUid >= 0) {
15976                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15977                                    verificationInfo.installerUid);
15978                        }
15979                    }
15980
15981                    final PackageVerificationState verificationState = new PackageVerificationState(
15982                            requiredUid, args);
15983
15984                    mPendingVerification.append(verificationId, verificationState);
15985
15986                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15987                            receivers, verificationState);
15988
15989                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15990                    final long idleDuration = getVerificationTimeout();
15991
15992                    /*
15993                     * If any sufficient verifiers were listed in the package
15994                     * manifest, attempt to ask them.
15995                     */
15996                    if (sufficientVerifiers != null) {
15997                        final int N = sufficientVerifiers.size();
15998                        if (N == 0) {
15999                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16000                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16001                        } else {
16002                            for (int i = 0; i < N; i++) {
16003                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16004                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16005                                        verifierComponent.getPackageName(), idleDuration,
16006                                        verifierUser.getIdentifier(), false, "package verifier");
16007
16008                                final Intent sufficientIntent = new Intent(verification);
16009                                sufficientIntent.setComponent(verifierComponent);
16010                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16011                            }
16012                        }
16013                    }
16014
16015                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16016                            mRequiredVerifierPackage, receivers);
16017                    if (ret == PackageManager.INSTALL_SUCCEEDED
16018                            && mRequiredVerifierPackage != null) {
16019                        Trace.asyncTraceBegin(
16020                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16021                        /*
16022                         * Send the intent to the required verification agent,
16023                         * but only start the verification timeout after the
16024                         * target BroadcastReceivers have run.
16025                         */
16026                        verification.setComponent(requiredVerifierComponent);
16027                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16028                                mRequiredVerifierPackage, idleDuration,
16029                                verifierUser.getIdentifier(), false, "package verifier");
16030                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16031                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16032                                new BroadcastReceiver() {
16033                                    @Override
16034                                    public void onReceive(Context context, Intent intent) {
16035                                        final Message msg = mHandler
16036                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16037                                        msg.arg1 = verificationId;
16038                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16039                                    }
16040                                }, null, 0, null, null);
16041
16042                        /*
16043                         * We don't want the copy to proceed until verification
16044                         * succeeds, so null out this field.
16045                         */
16046                        mArgs = null;
16047                    }
16048                } else {
16049                    /*
16050                     * No package verification is enabled, so immediately start
16051                     * the remote call to initiate copy using temporary file.
16052                     */
16053                    ret = args.copyApk(mContainerService, true);
16054                }
16055            }
16056
16057            mRet = ret;
16058        }
16059
16060        @Override
16061        void handleReturnCode() {
16062            // If mArgs is null, then MCS couldn't be reached. When it
16063            // reconnects, it will try again to install. At that point, this
16064            // will succeed.
16065            if (mArgs != null) {
16066                processPendingInstall(mArgs, mRet);
16067            }
16068        }
16069
16070        @Override
16071        void handleServiceError() {
16072            mArgs = createInstallArgs(this);
16073            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16074        }
16075
16076        public boolean isForwardLocked() {
16077            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16078        }
16079    }
16080
16081    /**
16082     * Used during creation of InstallArgs
16083     *
16084     * @param installFlags package installation flags
16085     * @return true if should be installed on external storage
16086     */
16087    private static boolean installOnExternalAsec(int installFlags) {
16088        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16089            return false;
16090        }
16091        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16092            return true;
16093        }
16094        return false;
16095    }
16096
16097    /**
16098     * Used during creation of InstallArgs
16099     *
16100     * @param installFlags package installation flags
16101     * @return true if should be installed as forward locked
16102     */
16103    private static boolean installForwardLocked(int installFlags) {
16104        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16105    }
16106
16107    private InstallArgs createInstallArgs(InstallParams params) {
16108        if (params.move != null) {
16109            return new MoveInstallArgs(params);
16110        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16111            return new AsecInstallArgs(params);
16112        } else {
16113            return new FileInstallArgs(params);
16114        }
16115    }
16116
16117    /**
16118     * Create args that describe an existing installed package. Typically used
16119     * when cleaning up old installs, or used as a move source.
16120     */
16121    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16122            String resourcePath, String[] instructionSets) {
16123        final boolean isInAsec;
16124        if (installOnExternalAsec(installFlags)) {
16125            /* Apps on SD card are always in ASEC containers. */
16126            isInAsec = true;
16127        } else if (installForwardLocked(installFlags)
16128                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16129            /*
16130             * Forward-locked apps are only in ASEC containers if they're the
16131             * new style
16132             */
16133            isInAsec = true;
16134        } else {
16135            isInAsec = false;
16136        }
16137
16138        if (isInAsec) {
16139            return new AsecInstallArgs(codePath, instructionSets,
16140                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16141        } else {
16142            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16143        }
16144    }
16145
16146    static abstract class InstallArgs {
16147        /** @see InstallParams#origin */
16148        final OriginInfo origin;
16149        /** @see InstallParams#move */
16150        final MoveInfo move;
16151
16152        final IPackageInstallObserver2 observer;
16153        // Always refers to PackageManager flags only
16154        final int installFlags;
16155        final String installerPackageName;
16156        final String volumeUuid;
16157        final UserHandle user;
16158        final String abiOverride;
16159        final String[] installGrantPermissions;
16160        /** If non-null, drop an async trace when the install completes */
16161        final String traceMethod;
16162        final int traceCookie;
16163        final Certificate[][] certificates;
16164        final int installReason;
16165
16166        // The list of instruction sets supported by this app. This is currently
16167        // only used during the rmdex() phase to clean up resources. We can get rid of this
16168        // if we move dex files under the common app path.
16169        /* nullable */ String[] instructionSets;
16170
16171        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16172                int installFlags, String installerPackageName, String volumeUuid,
16173                UserHandle user, String[] instructionSets,
16174                String abiOverride, String[] installGrantPermissions,
16175                String traceMethod, int traceCookie, Certificate[][] certificates,
16176                int installReason) {
16177            this.origin = origin;
16178            this.move = move;
16179            this.installFlags = installFlags;
16180            this.observer = observer;
16181            this.installerPackageName = installerPackageName;
16182            this.volumeUuid = volumeUuid;
16183            this.user = user;
16184            this.instructionSets = instructionSets;
16185            this.abiOverride = abiOverride;
16186            this.installGrantPermissions = installGrantPermissions;
16187            this.traceMethod = traceMethod;
16188            this.traceCookie = traceCookie;
16189            this.certificates = certificates;
16190            this.installReason = installReason;
16191        }
16192
16193        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16194        abstract int doPreInstall(int status);
16195
16196        /**
16197         * Rename package into final resting place. All paths on the given
16198         * scanned package should be updated to reflect the rename.
16199         */
16200        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16201        abstract int doPostInstall(int status, int uid);
16202
16203        /** @see PackageSettingBase#codePathString */
16204        abstract String getCodePath();
16205        /** @see PackageSettingBase#resourcePathString */
16206        abstract String getResourcePath();
16207
16208        // Need installer lock especially for dex file removal.
16209        abstract void cleanUpResourcesLI();
16210        abstract boolean doPostDeleteLI(boolean delete);
16211
16212        /**
16213         * Called before the source arguments are copied. This is used mostly
16214         * for MoveParams when it needs to read the source file to put it in the
16215         * destination.
16216         */
16217        int doPreCopy() {
16218            return PackageManager.INSTALL_SUCCEEDED;
16219        }
16220
16221        /**
16222         * Called after the source arguments are copied. This is used mostly for
16223         * MoveParams when it needs to read the source file to put it in the
16224         * destination.
16225         */
16226        int doPostCopy(int uid) {
16227            return PackageManager.INSTALL_SUCCEEDED;
16228        }
16229
16230        protected boolean isFwdLocked() {
16231            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16232        }
16233
16234        protected boolean isExternalAsec() {
16235            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16236        }
16237
16238        protected boolean isEphemeral() {
16239            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16240        }
16241
16242        UserHandle getUser() {
16243            return user;
16244        }
16245    }
16246
16247    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16248        if (!allCodePaths.isEmpty()) {
16249            if (instructionSets == null) {
16250                throw new IllegalStateException("instructionSet == null");
16251            }
16252            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16253            for (String codePath : allCodePaths) {
16254                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16255                    try {
16256                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16257                    } catch (InstallerException ignored) {
16258                    }
16259                }
16260            }
16261        }
16262    }
16263
16264    /**
16265     * Logic to handle installation of non-ASEC applications, including copying
16266     * and renaming logic.
16267     */
16268    class FileInstallArgs extends InstallArgs {
16269        private File codeFile;
16270        private File resourceFile;
16271
16272        // Example topology:
16273        // /data/app/com.example/base.apk
16274        // /data/app/com.example/split_foo.apk
16275        // /data/app/com.example/lib/arm/libfoo.so
16276        // /data/app/com.example/lib/arm64/libfoo.so
16277        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16278
16279        /** New install */
16280        FileInstallArgs(InstallParams params) {
16281            super(params.origin, params.move, params.observer, params.installFlags,
16282                    params.installerPackageName, params.volumeUuid,
16283                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16284                    params.grantedRuntimePermissions,
16285                    params.traceMethod, params.traceCookie, params.certificates,
16286                    params.installReason);
16287            if (isFwdLocked()) {
16288                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16289            }
16290        }
16291
16292        /** Existing install */
16293        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16294            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16295                    null, null, null, 0, null /*certificates*/,
16296                    PackageManager.INSTALL_REASON_UNKNOWN);
16297            this.codeFile = (codePath != null) ? new File(codePath) : null;
16298            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16299        }
16300
16301        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16302            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16303            try {
16304                return doCopyApk(imcs, temp);
16305            } finally {
16306                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16307            }
16308        }
16309
16310        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16311            if (origin.staged) {
16312                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16313                codeFile = origin.file;
16314                resourceFile = origin.file;
16315                return PackageManager.INSTALL_SUCCEEDED;
16316            }
16317
16318            try {
16319                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16320                final File tempDir =
16321                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16322                codeFile = tempDir;
16323                resourceFile = tempDir;
16324            } catch (IOException e) {
16325                Slog.w(TAG, "Failed to create copy file: " + e);
16326                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16327            }
16328
16329            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16330                @Override
16331                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16332                    if (!FileUtils.isValidExtFilename(name)) {
16333                        throw new IllegalArgumentException("Invalid filename: " + name);
16334                    }
16335                    try {
16336                        final File file = new File(codeFile, name);
16337                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16338                                O_RDWR | O_CREAT, 0644);
16339                        Os.chmod(file.getAbsolutePath(), 0644);
16340                        return new ParcelFileDescriptor(fd);
16341                    } catch (ErrnoException e) {
16342                        throw new RemoteException("Failed to open: " + e.getMessage());
16343                    }
16344                }
16345            };
16346
16347            int ret = PackageManager.INSTALL_SUCCEEDED;
16348            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16349            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16350                Slog.e(TAG, "Failed to copy package");
16351                return ret;
16352            }
16353
16354            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16355            NativeLibraryHelper.Handle handle = null;
16356            try {
16357                handle = NativeLibraryHelper.Handle.create(codeFile);
16358                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16359                        abiOverride);
16360            } catch (IOException e) {
16361                Slog.e(TAG, "Copying native libraries failed", e);
16362                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16363            } finally {
16364                IoUtils.closeQuietly(handle);
16365            }
16366
16367            return ret;
16368        }
16369
16370        int doPreInstall(int status) {
16371            if (status != PackageManager.INSTALL_SUCCEEDED) {
16372                cleanUp();
16373            }
16374            return status;
16375        }
16376
16377        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16378            if (status != PackageManager.INSTALL_SUCCEEDED) {
16379                cleanUp();
16380                return false;
16381            }
16382
16383            final File targetDir = codeFile.getParentFile();
16384            final File beforeCodeFile = codeFile;
16385            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16386
16387            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16388            try {
16389                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16390            } catch (ErrnoException e) {
16391                Slog.w(TAG, "Failed to rename", e);
16392                return false;
16393            }
16394
16395            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16396                Slog.w(TAG, "Failed to restorecon");
16397                return false;
16398            }
16399
16400            // Reflect the rename internally
16401            codeFile = afterCodeFile;
16402            resourceFile = afterCodeFile;
16403
16404            // Reflect the rename in scanned details
16405            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16406            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16407                    afterCodeFile, pkg.baseCodePath));
16408            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16409                    afterCodeFile, pkg.splitCodePaths));
16410
16411            // Reflect the rename in app info
16412            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16413            pkg.setApplicationInfoCodePath(pkg.codePath);
16414            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16415            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16416            pkg.setApplicationInfoResourcePath(pkg.codePath);
16417            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16418            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16419
16420            return true;
16421        }
16422
16423        int doPostInstall(int status, int uid) {
16424            if (status != PackageManager.INSTALL_SUCCEEDED) {
16425                cleanUp();
16426            }
16427            return status;
16428        }
16429
16430        @Override
16431        String getCodePath() {
16432            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16433        }
16434
16435        @Override
16436        String getResourcePath() {
16437            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16438        }
16439
16440        private boolean cleanUp() {
16441            if (codeFile == null || !codeFile.exists()) {
16442                return false;
16443            }
16444
16445            removeCodePathLI(codeFile);
16446
16447            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16448                resourceFile.delete();
16449            }
16450
16451            return true;
16452        }
16453
16454        void cleanUpResourcesLI() {
16455            // Try enumerating all code paths before deleting
16456            List<String> allCodePaths = Collections.EMPTY_LIST;
16457            if (codeFile != null && codeFile.exists()) {
16458                try {
16459                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16460                    allCodePaths = pkg.getAllCodePaths();
16461                } catch (PackageParserException e) {
16462                    // Ignored; we tried our best
16463                }
16464            }
16465
16466            cleanUp();
16467            removeDexFiles(allCodePaths, instructionSets);
16468        }
16469
16470        boolean doPostDeleteLI(boolean delete) {
16471            // XXX err, shouldn't we respect the delete flag?
16472            cleanUpResourcesLI();
16473            return true;
16474        }
16475    }
16476
16477    private boolean isAsecExternal(String cid) {
16478        final String asecPath = PackageHelper.getSdFilesystem(cid);
16479        return !asecPath.startsWith(mAsecInternalPath);
16480    }
16481
16482    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16483            PackageManagerException {
16484        if (copyRet < 0) {
16485            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16486                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16487                throw new PackageManagerException(copyRet, message);
16488            }
16489        }
16490    }
16491
16492    /**
16493     * Extract the StorageManagerService "container ID" from the full code path of an
16494     * .apk.
16495     */
16496    static String cidFromCodePath(String fullCodePath) {
16497        int eidx = fullCodePath.lastIndexOf("/");
16498        String subStr1 = fullCodePath.substring(0, eidx);
16499        int sidx = subStr1.lastIndexOf("/");
16500        return subStr1.substring(sidx+1, eidx);
16501    }
16502
16503    /**
16504     * Logic to handle installation of ASEC applications, including copying and
16505     * renaming logic.
16506     */
16507    class AsecInstallArgs extends InstallArgs {
16508        static final String RES_FILE_NAME = "pkg.apk";
16509        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16510
16511        String cid;
16512        String packagePath;
16513        String resourcePath;
16514
16515        /** New install */
16516        AsecInstallArgs(InstallParams params) {
16517            super(params.origin, params.move, params.observer, params.installFlags,
16518                    params.installerPackageName, params.volumeUuid,
16519                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16520                    params.grantedRuntimePermissions,
16521                    params.traceMethod, params.traceCookie, params.certificates,
16522                    params.installReason);
16523        }
16524
16525        /** Existing install */
16526        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16527                        boolean isExternal, boolean isForwardLocked) {
16528            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16529                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16530                    instructionSets, null, null, null, 0, null /*certificates*/,
16531                    PackageManager.INSTALL_REASON_UNKNOWN);
16532            // Hackily pretend we're still looking at a full code path
16533            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16534                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16535            }
16536
16537            // Extract cid from fullCodePath
16538            int eidx = fullCodePath.lastIndexOf("/");
16539            String subStr1 = fullCodePath.substring(0, eidx);
16540            int sidx = subStr1.lastIndexOf("/");
16541            cid = subStr1.substring(sidx+1, eidx);
16542            setMountPath(subStr1);
16543        }
16544
16545        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16546            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16547                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16548                    instructionSets, null, null, null, 0, null /*certificates*/,
16549                    PackageManager.INSTALL_REASON_UNKNOWN);
16550            this.cid = cid;
16551            setMountPath(PackageHelper.getSdDir(cid));
16552        }
16553
16554        void createCopyFile() {
16555            cid = mInstallerService.allocateExternalStageCidLegacy();
16556        }
16557
16558        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16559            if (origin.staged && origin.cid != null) {
16560                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16561                cid = origin.cid;
16562                setMountPath(PackageHelper.getSdDir(cid));
16563                return PackageManager.INSTALL_SUCCEEDED;
16564            }
16565
16566            if (temp) {
16567                createCopyFile();
16568            } else {
16569                /*
16570                 * Pre-emptively destroy the container since it's destroyed if
16571                 * copying fails due to it existing anyway.
16572                 */
16573                PackageHelper.destroySdDir(cid);
16574            }
16575
16576            final String newMountPath = imcs.copyPackageToContainer(
16577                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16578                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16579
16580            if (newMountPath != null) {
16581                setMountPath(newMountPath);
16582                return PackageManager.INSTALL_SUCCEEDED;
16583            } else {
16584                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16585            }
16586        }
16587
16588        @Override
16589        String getCodePath() {
16590            return packagePath;
16591        }
16592
16593        @Override
16594        String getResourcePath() {
16595            return resourcePath;
16596        }
16597
16598        int doPreInstall(int status) {
16599            if (status != PackageManager.INSTALL_SUCCEEDED) {
16600                // Destroy container
16601                PackageHelper.destroySdDir(cid);
16602            } else {
16603                boolean mounted = PackageHelper.isContainerMounted(cid);
16604                if (!mounted) {
16605                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16606                            Process.SYSTEM_UID);
16607                    if (newMountPath != null) {
16608                        setMountPath(newMountPath);
16609                    } else {
16610                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16611                    }
16612                }
16613            }
16614            return status;
16615        }
16616
16617        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16618            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16619            String newMountPath = null;
16620            if (PackageHelper.isContainerMounted(cid)) {
16621                // Unmount the container
16622                if (!PackageHelper.unMountSdDir(cid)) {
16623                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16624                    return false;
16625                }
16626            }
16627            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16628                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16629                        " which might be stale. Will try to clean up.");
16630                // Clean up the stale container and proceed to recreate.
16631                if (!PackageHelper.destroySdDir(newCacheId)) {
16632                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16633                    return false;
16634                }
16635                // Successfully cleaned up stale container. Try to rename again.
16636                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16637                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16638                            + " inspite of cleaning it up.");
16639                    return false;
16640                }
16641            }
16642            if (!PackageHelper.isContainerMounted(newCacheId)) {
16643                Slog.w(TAG, "Mounting container " + newCacheId);
16644                newMountPath = PackageHelper.mountSdDir(newCacheId,
16645                        getEncryptKey(), Process.SYSTEM_UID);
16646            } else {
16647                newMountPath = PackageHelper.getSdDir(newCacheId);
16648            }
16649            if (newMountPath == null) {
16650                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16651                return false;
16652            }
16653            Log.i(TAG, "Succesfully renamed " + cid +
16654                    " to " + newCacheId +
16655                    " at new path: " + newMountPath);
16656            cid = newCacheId;
16657
16658            final File beforeCodeFile = new File(packagePath);
16659            setMountPath(newMountPath);
16660            final File afterCodeFile = new File(packagePath);
16661
16662            // Reflect the rename in scanned details
16663            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16664            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16665                    afterCodeFile, pkg.baseCodePath));
16666            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16667                    afterCodeFile, pkg.splitCodePaths));
16668
16669            // Reflect the rename in app info
16670            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16671            pkg.setApplicationInfoCodePath(pkg.codePath);
16672            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16673            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16674            pkg.setApplicationInfoResourcePath(pkg.codePath);
16675            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16676            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16677
16678            return true;
16679        }
16680
16681        private void setMountPath(String mountPath) {
16682            final File mountFile = new File(mountPath);
16683
16684            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16685            if (monolithicFile.exists()) {
16686                packagePath = monolithicFile.getAbsolutePath();
16687                if (isFwdLocked()) {
16688                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16689                } else {
16690                    resourcePath = packagePath;
16691                }
16692            } else {
16693                packagePath = mountFile.getAbsolutePath();
16694                resourcePath = packagePath;
16695            }
16696        }
16697
16698        int doPostInstall(int status, int uid) {
16699            if (status != PackageManager.INSTALL_SUCCEEDED) {
16700                cleanUp();
16701            } else {
16702                final int groupOwner;
16703                final String protectedFile;
16704                if (isFwdLocked()) {
16705                    groupOwner = UserHandle.getSharedAppGid(uid);
16706                    protectedFile = RES_FILE_NAME;
16707                } else {
16708                    groupOwner = -1;
16709                    protectedFile = null;
16710                }
16711
16712                if (uid < Process.FIRST_APPLICATION_UID
16713                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16714                    Slog.e(TAG, "Failed to finalize " + cid);
16715                    PackageHelper.destroySdDir(cid);
16716                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16717                }
16718
16719                boolean mounted = PackageHelper.isContainerMounted(cid);
16720                if (!mounted) {
16721                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16722                }
16723            }
16724            return status;
16725        }
16726
16727        private void cleanUp() {
16728            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16729
16730            // Destroy secure container
16731            PackageHelper.destroySdDir(cid);
16732        }
16733
16734        private List<String> getAllCodePaths() {
16735            final File codeFile = new File(getCodePath());
16736            if (codeFile != null && codeFile.exists()) {
16737                try {
16738                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16739                    return pkg.getAllCodePaths();
16740                } catch (PackageParserException e) {
16741                    // Ignored; we tried our best
16742                }
16743            }
16744            return Collections.EMPTY_LIST;
16745        }
16746
16747        void cleanUpResourcesLI() {
16748            // Enumerate all code paths before deleting
16749            cleanUpResourcesLI(getAllCodePaths());
16750        }
16751
16752        private void cleanUpResourcesLI(List<String> allCodePaths) {
16753            cleanUp();
16754            removeDexFiles(allCodePaths, instructionSets);
16755        }
16756
16757        String getPackageName() {
16758            return getAsecPackageName(cid);
16759        }
16760
16761        boolean doPostDeleteLI(boolean delete) {
16762            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16763            final List<String> allCodePaths = getAllCodePaths();
16764            boolean mounted = PackageHelper.isContainerMounted(cid);
16765            if (mounted) {
16766                // Unmount first
16767                if (PackageHelper.unMountSdDir(cid)) {
16768                    mounted = false;
16769                }
16770            }
16771            if (!mounted && delete) {
16772                cleanUpResourcesLI(allCodePaths);
16773            }
16774            return !mounted;
16775        }
16776
16777        @Override
16778        int doPreCopy() {
16779            if (isFwdLocked()) {
16780                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16781                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16782                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16783                }
16784            }
16785
16786            return PackageManager.INSTALL_SUCCEEDED;
16787        }
16788
16789        @Override
16790        int doPostCopy(int uid) {
16791            if (isFwdLocked()) {
16792                if (uid < Process.FIRST_APPLICATION_UID
16793                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16794                                RES_FILE_NAME)) {
16795                    Slog.e(TAG, "Failed to finalize " + cid);
16796                    PackageHelper.destroySdDir(cid);
16797                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16798                }
16799            }
16800
16801            return PackageManager.INSTALL_SUCCEEDED;
16802        }
16803    }
16804
16805    /**
16806     * Logic to handle movement of existing installed applications.
16807     */
16808    class MoveInstallArgs extends InstallArgs {
16809        private File codeFile;
16810        private File resourceFile;
16811
16812        /** New install */
16813        MoveInstallArgs(InstallParams params) {
16814            super(params.origin, params.move, params.observer, params.installFlags,
16815                    params.installerPackageName, params.volumeUuid,
16816                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16817                    params.grantedRuntimePermissions,
16818                    params.traceMethod, params.traceCookie, params.certificates,
16819                    params.installReason);
16820        }
16821
16822        int copyApk(IMediaContainerService imcs, boolean temp) {
16823            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16824                    + move.fromUuid + " to " + move.toUuid);
16825            synchronized (mInstaller) {
16826                try {
16827                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16828                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16829                } catch (InstallerException e) {
16830                    Slog.w(TAG, "Failed to move app", e);
16831                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16832                }
16833            }
16834
16835            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16836            resourceFile = codeFile;
16837            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16838
16839            return PackageManager.INSTALL_SUCCEEDED;
16840        }
16841
16842        int doPreInstall(int status) {
16843            if (status != PackageManager.INSTALL_SUCCEEDED) {
16844                cleanUp(move.toUuid);
16845            }
16846            return status;
16847        }
16848
16849        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16850            if (status != PackageManager.INSTALL_SUCCEEDED) {
16851                cleanUp(move.toUuid);
16852                return false;
16853            }
16854
16855            // Reflect the move in app info
16856            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16857            pkg.setApplicationInfoCodePath(pkg.codePath);
16858            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16859            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16860            pkg.setApplicationInfoResourcePath(pkg.codePath);
16861            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16862            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16863
16864            return true;
16865        }
16866
16867        int doPostInstall(int status, int uid) {
16868            if (status == PackageManager.INSTALL_SUCCEEDED) {
16869                cleanUp(move.fromUuid);
16870            } else {
16871                cleanUp(move.toUuid);
16872            }
16873            return status;
16874        }
16875
16876        @Override
16877        String getCodePath() {
16878            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16879        }
16880
16881        @Override
16882        String getResourcePath() {
16883            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16884        }
16885
16886        private boolean cleanUp(String volumeUuid) {
16887            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16888                    move.dataAppName);
16889            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16890            final int[] userIds = sUserManager.getUserIds();
16891            synchronized (mInstallLock) {
16892                // Clean up both app data and code
16893                // All package moves are frozen until finished
16894                for (int userId : userIds) {
16895                    try {
16896                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16897                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16898                    } catch (InstallerException e) {
16899                        Slog.w(TAG, String.valueOf(e));
16900                    }
16901                }
16902                removeCodePathLI(codeFile);
16903            }
16904            return true;
16905        }
16906
16907        void cleanUpResourcesLI() {
16908            throw new UnsupportedOperationException();
16909        }
16910
16911        boolean doPostDeleteLI(boolean delete) {
16912            throw new UnsupportedOperationException();
16913        }
16914    }
16915
16916    static String getAsecPackageName(String packageCid) {
16917        int idx = packageCid.lastIndexOf("-");
16918        if (idx == -1) {
16919            return packageCid;
16920        }
16921        return packageCid.substring(0, idx);
16922    }
16923
16924    // Utility method used to create code paths based on package name and available index.
16925    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16926        String idxStr = "";
16927        int idx = 1;
16928        // Fall back to default value of idx=1 if prefix is not
16929        // part of oldCodePath
16930        if (oldCodePath != null) {
16931            String subStr = oldCodePath;
16932            // Drop the suffix right away
16933            if (suffix != null && subStr.endsWith(suffix)) {
16934                subStr = subStr.substring(0, subStr.length() - suffix.length());
16935            }
16936            // If oldCodePath already contains prefix find out the
16937            // ending index to either increment or decrement.
16938            int sidx = subStr.lastIndexOf(prefix);
16939            if (sidx != -1) {
16940                subStr = subStr.substring(sidx + prefix.length());
16941                if (subStr != null) {
16942                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16943                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16944                    }
16945                    try {
16946                        idx = Integer.parseInt(subStr);
16947                        if (idx <= 1) {
16948                            idx++;
16949                        } else {
16950                            idx--;
16951                        }
16952                    } catch(NumberFormatException e) {
16953                    }
16954                }
16955            }
16956        }
16957        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16958        return prefix + idxStr;
16959    }
16960
16961    private File getNextCodePath(File targetDir, String packageName) {
16962        File result;
16963        SecureRandom random = new SecureRandom();
16964        byte[] bytes = new byte[16];
16965        do {
16966            random.nextBytes(bytes);
16967            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16968            result = new File(targetDir, packageName + "-" + suffix);
16969        } while (result.exists());
16970        return result;
16971    }
16972
16973    // Utility method that returns the relative package path with respect
16974    // to the installation directory. Like say for /data/data/com.test-1.apk
16975    // string com.test-1 is returned.
16976    static String deriveCodePathName(String codePath) {
16977        if (codePath == null) {
16978            return null;
16979        }
16980        final File codeFile = new File(codePath);
16981        final String name = codeFile.getName();
16982        if (codeFile.isDirectory()) {
16983            return name;
16984        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16985            final int lastDot = name.lastIndexOf('.');
16986            return name.substring(0, lastDot);
16987        } else {
16988            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16989            return null;
16990        }
16991    }
16992
16993    static class PackageInstalledInfo {
16994        String name;
16995        int uid;
16996        // The set of users that originally had this package installed.
16997        int[] origUsers;
16998        // The set of users that now have this package installed.
16999        int[] newUsers;
17000        PackageParser.Package pkg;
17001        int returnCode;
17002        String returnMsg;
17003        PackageRemovedInfo removedInfo;
17004        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17005
17006        public void setError(int code, String msg) {
17007            setReturnCode(code);
17008            setReturnMessage(msg);
17009            Slog.w(TAG, msg);
17010        }
17011
17012        public void setError(String msg, PackageParserException e) {
17013            setReturnCode(e.error);
17014            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17015            Slog.w(TAG, msg, e);
17016        }
17017
17018        public void setError(String msg, PackageManagerException e) {
17019            returnCode = e.error;
17020            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17021            Slog.w(TAG, msg, e);
17022        }
17023
17024        public void setReturnCode(int returnCode) {
17025            this.returnCode = returnCode;
17026            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17027            for (int i = 0; i < childCount; i++) {
17028                addedChildPackages.valueAt(i).returnCode = returnCode;
17029            }
17030        }
17031
17032        private void setReturnMessage(String returnMsg) {
17033            this.returnMsg = returnMsg;
17034            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17035            for (int i = 0; i < childCount; i++) {
17036                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17037            }
17038        }
17039
17040        // In some error cases we want to convey more info back to the observer
17041        String origPackage;
17042        String origPermission;
17043    }
17044
17045    /*
17046     * Install a non-existing package.
17047     */
17048    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17049            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17050            PackageInstalledInfo res, int installReason) {
17051        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17052
17053        // Remember this for later, in case we need to rollback this install
17054        String pkgName = pkg.packageName;
17055
17056        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17057
17058        synchronized(mPackages) {
17059            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17060            if (renamedPackage != null) {
17061                // A package with the same name is already installed, though
17062                // it has been renamed to an older name.  The package we
17063                // are trying to install should be installed as an update to
17064                // the existing one, but that has not been requested, so bail.
17065                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17066                        + " without first uninstalling package running as "
17067                        + renamedPackage);
17068                return;
17069            }
17070            if (mPackages.containsKey(pkgName)) {
17071                // Don't allow installation over an existing package with the same name.
17072                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17073                        + " without first uninstalling.");
17074                return;
17075            }
17076        }
17077
17078        try {
17079            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17080                    System.currentTimeMillis(), user);
17081
17082            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17083
17084            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17085                prepareAppDataAfterInstallLIF(newPackage);
17086
17087            } else {
17088                // Remove package from internal structures, but keep around any
17089                // data that might have already existed
17090                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17091                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17092            }
17093        } catch (PackageManagerException e) {
17094            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17095        }
17096
17097        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17098    }
17099
17100    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17101        // Can't rotate keys during boot or if sharedUser.
17102        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17103                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17104            return false;
17105        }
17106        // app is using upgradeKeySets; make sure all are valid
17107        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17108        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17109        for (int i = 0; i < upgradeKeySets.length; i++) {
17110            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17111                Slog.wtf(TAG, "Package "
17112                         + (oldPs.name != null ? oldPs.name : "<null>")
17113                         + " contains upgrade-key-set reference to unknown key-set: "
17114                         + upgradeKeySets[i]
17115                         + " reverting to signatures check.");
17116                return false;
17117            }
17118        }
17119        return true;
17120    }
17121
17122    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17123        // Upgrade keysets are being used.  Determine if new package has a superset of the
17124        // required keys.
17125        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17126        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17127        for (int i = 0; i < upgradeKeySets.length; i++) {
17128            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17129            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17130                return true;
17131            }
17132        }
17133        return false;
17134    }
17135
17136    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17137        try (DigestInputStream digestStream =
17138                new DigestInputStream(new FileInputStream(file), digest)) {
17139            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17140        }
17141    }
17142
17143    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17144            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17145            int installReason) {
17146        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17147
17148        final PackageParser.Package oldPackage;
17149        final PackageSetting ps;
17150        final String pkgName = pkg.packageName;
17151        final int[] allUsers;
17152        final int[] installedUsers;
17153
17154        synchronized(mPackages) {
17155            oldPackage = mPackages.get(pkgName);
17156            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17157
17158            // don't allow upgrade to target a release SDK from a pre-release SDK
17159            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17160                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17161            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17162                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17163            if (oldTargetsPreRelease
17164                    && !newTargetsPreRelease
17165                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17166                Slog.w(TAG, "Can't install package targeting released sdk");
17167                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17168                return;
17169            }
17170
17171            ps = mSettings.mPackages.get(pkgName);
17172
17173            // verify signatures are valid
17174            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17175                if (!checkUpgradeKeySetLP(ps, pkg)) {
17176                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17177                            "New package not signed by keys specified by upgrade-keysets: "
17178                                    + pkgName);
17179                    return;
17180                }
17181            } else {
17182                // default to original signature matching
17183                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17184                        != PackageManager.SIGNATURE_MATCH) {
17185                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17186                            "New package has a different signature: " + pkgName);
17187                    return;
17188                }
17189            }
17190
17191            // don't allow a system upgrade unless the upgrade hash matches
17192            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17193                byte[] digestBytes = null;
17194                try {
17195                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17196                    updateDigest(digest, new File(pkg.baseCodePath));
17197                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17198                        for (String path : pkg.splitCodePaths) {
17199                            updateDigest(digest, new File(path));
17200                        }
17201                    }
17202                    digestBytes = digest.digest();
17203                } catch (NoSuchAlgorithmException | IOException e) {
17204                    res.setError(INSTALL_FAILED_INVALID_APK,
17205                            "Could not compute hash: " + pkgName);
17206                    return;
17207                }
17208                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17209                    res.setError(INSTALL_FAILED_INVALID_APK,
17210                            "New package fails restrict-update check: " + pkgName);
17211                    return;
17212                }
17213                // retain upgrade restriction
17214                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17215            }
17216
17217            // Check for shared user id changes
17218            String invalidPackageName =
17219                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17220            if (invalidPackageName != null) {
17221                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17222                        "Package " + invalidPackageName + " tried to change user "
17223                                + oldPackage.mSharedUserId);
17224                return;
17225            }
17226
17227            // check if the new package supports all of the abis which the old package supports
17228            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
17229            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
17230            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
17231                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17232                        "Update to package " + pkgName + " doesn't support multi arch");
17233                return;
17234            }
17235
17236            // In case of rollback, remember per-user/profile install state
17237            allUsers = sUserManager.getUserIds();
17238            installedUsers = ps.queryInstalledUsers(allUsers, true);
17239
17240            // don't allow an upgrade from full to ephemeral
17241            if (isInstantApp) {
17242                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17243                    for (int currentUser : allUsers) {
17244                        if (!ps.getInstantApp(currentUser)) {
17245                            // can't downgrade from full to instant
17246                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17247                                    + " for user: " + currentUser);
17248                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17249                            return;
17250                        }
17251                    }
17252                } else if (!ps.getInstantApp(user.getIdentifier())) {
17253                    // can't downgrade from full to instant
17254                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17255                            + " for user: " + user.getIdentifier());
17256                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17257                    return;
17258                }
17259            }
17260        }
17261
17262        // Update what is removed
17263        res.removedInfo = new PackageRemovedInfo(this);
17264        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17265        res.removedInfo.removedPackage = oldPackage.packageName;
17266        res.removedInfo.installerPackageName = ps.installerPackageName;
17267        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17268        res.removedInfo.isUpdate = true;
17269        res.removedInfo.origUsers = installedUsers;
17270        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17271        for (int i = 0; i < installedUsers.length; i++) {
17272            final int userId = installedUsers[i];
17273            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17274        }
17275
17276        final int childCount = (oldPackage.childPackages != null)
17277                ? oldPackage.childPackages.size() : 0;
17278        for (int i = 0; i < childCount; i++) {
17279            boolean childPackageUpdated = false;
17280            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17281            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17282            if (res.addedChildPackages != null) {
17283                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17284                if (childRes != null) {
17285                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17286                    childRes.removedInfo.removedPackage = childPkg.packageName;
17287                    if (childPs != null) {
17288                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17289                    }
17290                    childRes.removedInfo.isUpdate = true;
17291                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17292                    childPackageUpdated = true;
17293                }
17294            }
17295            if (!childPackageUpdated) {
17296                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17297                childRemovedRes.removedPackage = childPkg.packageName;
17298                if (childPs != null) {
17299                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17300                }
17301                childRemovedRes.isUpdate = false;
17302                childRemovedRes.dataRemoved = true;
17303                synchronized (mPackages) {
17304                    if (childPs != null) {
17305                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17306                    }
17307                }
17308                if (res.removedInfo.removedChildPackages == null) {
17309                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17310                }
17311                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17312            }
17313        }
17314
17315        boolean sysPkg = (isSystemApp(oldPackage));
17316        if (sysPkg) {
17317            // Set the system/privileged flags as needed
17318            final boolean privileged =
17319                    (oldPackage.applicationInfo.privateFlags
17320                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17321            final int systemPolicyFlags = policyFlags
17322                    | PackageParser.PARSE_IS_SYSTEM
17323                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17324
17325            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17326                    user, allUsers, installerPackageName, res, installReason);
17327        } else {
17328            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17329                    user, allUsers, installerPackageName, res, installReason);
17330        }
17331    }
17332
17333    @Override
17334    public List<String> getPreviousCodePaths(String packageName) {
17335        final int callingUid = Binder.getCallingUid();
17336        final List<String> result = new ArrayList<>();
17337        if (getInstantAppPackageName(callingUid) != null) {
17338            return result;
17339        }
17340        final PackageSetting ps = mSettings.mPackages.get(packageName);
17341        if (ps != null
17342                && ps.oldCodePaths != null
17343                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17344            result.addAll(ps.oldCodePaths);
17345        }
17346        return result;
17347    }
17348
17349    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17350            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17351            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17352            int installReason) {
17353        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17354                + deletedPackage);
17355
17356        String pkgName = deletedPackage.packageName;
17357        boolean deletedPkg = true;
17358        boolean addedPkg = false;
17359        boolean updatedSettings = false;
17360        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17361        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17362                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17363
17364        final long origUpdateTime = (pkg.mExtras != null)
17365                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17366
17367        // First delete the existing package while retaining the data directory
17368        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17369                res.removedInfo, true, pkg)) {
17370            // If the existing package wasn't successfully deleted
17371            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17372            deletedPkg = false;
17373        } else {
17374            // Successfully deleted the old package; proceed with replace.
17375
17376            // If deleted package lived in a container, give users a chance to
17377            // relinquish resources before killing.
17378            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17379                if (DEBUG_INSTALL) {
17380                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17381                }
17382                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17383                final ArrayList<String> pkgList = new ArrayList<String>(1);
17384                pkgList.add(deletedPackage.applicationInfo.packageName);
17385                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17386            }
17387
17388            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17389                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17390            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17391
17392            try {
17393                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17394                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17395                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17396                        installReason);
17397
17398                // Update the in-memory copy of the previous code paths.
17399                PackageSetting ps = mSettings.mPackages.get(pkgName);
17400                if (!killApp) {
17401                    if (ps.oldCodePaths == null) {
17402                        ps.oldCodePaths = new ArraySet<>();
17403                    }
17404                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17405                    if (deletedPackage.splitCodePaths != null) {
17406                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17407                    }
17408                } else {
17409                    ps.oldCodePaths = null;
17410                }
17411                if (ps.childPackageNames != null) {
17412                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17413                        final String childPkgName = ps.childPackageNames.get(i);
17414                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17415                        childPs.oldCodePaths = ps.oldCodePaths;
17416                    }
17417                }
17418                // set instant app status, but, only if it's explicitly specified
17419                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17420                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17421                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17422                prepareAppDataAfterInstallLIF(newPackage);
17423                addedPkg = true;
17424                mDexManager.notifyPackageUpdated(newPackage.packageName,
17425                        newPackage.baseCodePath, newPackage.splitCodePaths);
17426            } catch (PackageManagerException e) {
17427                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17428            }
17429        }
17430
17431        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17432            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17433
17434            // Revert all internal state mutations and added folders for the failed install
17435            if (addedPkg) {
17436                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17437                        res.removedInfo, true, null);
17438            }
17439
17440            // Restore the old package
17441            if (deletedPkg) {
17442                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17443                File restoreFile = new File(deletedPackage.codePath);
17444                // Parse old package
17445                boolean oldExternal = isExternal(deletedPackage);
17446                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17447                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17448                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17449                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17450                try {
17451                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17452                            null);
17453                } catch (PackageManagerException e) {
17454                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17455                            + e.getMessage());
17456                    return;
17457                }
17458
17459                synchronized (mPackages) {
17460                    // Ensure the installer package name up to date
17461                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17462
17463                    // Update permissions for restored package
17464                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17465
17466                    mSettings.writeLPr();
17467                }
17468
17469                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17470            }
17471        } else {
17472            synchronized (mPackages) {
17473                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17474                if (ps != null) {
17475                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17476                    if (res.removedInfo.removedChildPackages != null) {
17477                        final int childCount = res.removedInfo.removedChildPackages.size();
17478                        // Iterate in reverse as we may modify the collection
17479                        for (int i = childCount - 1; i >= 0; i--) {
17480                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17481                            if (res.addedChildPackages.containsKey(childPackageName)) {
17482                                res.removedInfo.removedChildPackages.removeAt(i);
17483                            } else {
17484                                PackageRemovedInfo childInfo = res.removedInfo
17485                                        .removedChildPackages.valueAt(i);
17486                                childInfo.removedForAllUsers = mPackages.get(
17487                                        childInfo.removedPackage) == null;
17488                            }
17489                        }
17490                    }
17491                }
17492            }
17493        }
17494    }
17495
17496    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17497            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17498            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17499            int installReason) {
17500        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17501                + ", old=" + deletedPackage);
17502
17503        final boolean disabledSystem;
17504
17505        // Remove existing system package
17506        removePackageLI(deletedPackage, true);
17507
17508        synchronized (mPackages) {
17509            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17510        }
17511        if (!disabledSystem) {
17512            // We didn't need to disable the .apk as a current system package,
17513            // which means we are replacing another update that is already
17514            // installed.  We need to make sure to delete the older one's .apk.
17515            res.removedInfo.args = createInstallArgsForExisting(0,
17516                    deletedPackage.applicationInfo.getCodePath(),
17517                    deletedPackage.applicationInfo.getResourcePath(),
17518                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17519        } else {
17520            res.removedInfo.args = null;
17521        }
17522
17523        // Successfully disabled the old package. Now proceed with re-installation
17524        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17525                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17526        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17527
17528        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17529        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17530                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17531
17532        PackageParser.Package newPackage = null;
17533        try {
17534            // Add the package to the internal data structures
17535            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17536
17537            // Set the update and install times
17538            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17539            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17540                    System.currentTimeMillis());
17541
17542            // Update the package dynamic state if succeeded
17543            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17544                // Now that the install succeeded make sure we remove data
17545                // directories for any child package the update removed.
17546                final int deletedChildCount = (deletedPackage.childPackages != null)
17547                        ? deletedPackage.childPackages.size() : 0;
17548                final int newChildCount = (newPackage.childPackages != null)
17549                        ? newPackage.childPackages.size() : 0;
17550                for (int i = 0; i < deletedChildCount; i++) {
17551                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17552                    boolean childPackageDeleted = true;
17553                    for (int j = 0; j < newChildCount; j++) {
17554                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17555                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17556                            childPackageDeleted = false;
17557                            break;
17558                        }
17559                    }
17560                    if (childPackageDeleted) {
17561                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17562                                deletedChildPkg.packageName);
17563                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17564                            PackageRemovedInfo removedChildRes = res.removedInfo
17565                                    .removedChildPackages.get(deletedChildPkg.packageName);
17566                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17567                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17568                        }
17569                    }
17570                }
17571
17572                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17573                        installReason);
17574                prepareAppDataAfterInstallLIF(newPackage);
17575
17576                mDexManager.notifyPackageUpdated(newPackage.packageName,
17577                            newPackage.baseCodePath, newPackage.splitCodePaths);
17578            }
17579        } catch (PackageManagerException e) {
17580            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17581            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17582        }
17583
17584        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17585            // Re installation failed. Restore old information
17586            // Remove new pkg information
17587            if (newPackage != null) {
17588                removeInstalledPackageLI(newPackage, true);
17589            }
17590            // Add back the old system package
17591            try {
17592                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17593            } catch (PackageManagerException e) {
17594                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17595            }
17596
17597            synchronized (mPackages) {
17598                if (disabledSystem) {
17599                    enableSystemPackageLPw(deletedPackage);
17600                }
17601
17602                // Ensure the installer package name up to date
17603                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17604
17605                // Update permissions for restored package
17606                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17607
17608                mSettings.writeLPr();
17609            }
17610
17611            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17612                    + " after failed upgrade");
17613        }
17614    }
17615
17616    /**
17617     * Checks whether the parent or any of the child packages have a change shared
17618     * user. For a package to be a valid update the shred users of the parent and
17619     * the children should match. We may later support changing child shared users.
17620     * @param oldPkg The updated package.
17621     * @param newPkg The update package.
17622     * @return The shared user that change between the versions.
17623     */
17624    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17625            PackageParser.Package newPkg) {
17626        // Check parent shared user
17627        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17628            return newPkg.packageName;
17629        }
17630        // Check child shared users
17631        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17632        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17633        for (int i = 0; i < newChildCount; i++) {
17634            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17635            // If this child was present, did it have the same shared user?
17636            for (int j = 0; j < oldChildCount; j++) {
17637                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17638                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17639                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17640                    return newChildPkg.packageName;
17641                }
17642            }
17643        }
17644        return null;
17645    }
17646
17647    private void removeNativeBinariesLI(PackageSetting ps) {
17648        // Remove the lib path for the parent package
17649        if (ps != null) {
17650            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17651            // Remove the lib path for the child packages
17652            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17653            for (int i = 0; i < childCount; i++) {
17654                PackageSetting childPs = null;
17655                synchronized (mPackages) {
17656                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17657                }
17658                if (childPs != null) {
17659                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17660                            .legacyNativeLibraryPathString);
17661                }
17662            }
17663        }
17664    }
17665
17666    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17667        // Enable the parent package
17668        mSettings.enableSystemPackageLPw(pkg.packageName);
17669        // Enable the child packages
17670        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17671        for (int i = 0; i < childCount; i++) {
17672            PackageParser.Package childPkg = pkg.childPackages.get(i);
17673            mSettings.enableSystemPackageLPw(childPkg.packageName);
17674        }
17675    }
17676
17677    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17678            PackageParser.Package newPkg) {
17679        // Disable the parent package (parent always replaced)
17680        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17681        // Disable the child packages
17682        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17683        for (int i = 0; i < childCount; i++) {
17684            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17685            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17686            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17687        }
17688        return disabled;
17689    }
17690
17691    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17692            String installerPackageName) {
17693        // Enable the parent package
17694        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17695        // Enable the child packages
17696        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17697        for (int i = 0; i < childCount; i++) {
17698            PackageParser.Package childPkg = pkg.childPackages.get(i);
17699            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17700        }
17701    }
17702
17703    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17704        // Collect all used permissions in the UID
17705        ArraySet<String> usedPermissions = new ArraySet<>();
17706        final int packageCount = su.packages.size();
17707        for (int i = 0; i < packageCount; i++) {
17708            PackageSetting ps = su.packages.valueAt(i);
17709            if (ps.pkg == null) {
17710                continue;
17711            }
17712            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17713            for (int j = 0; j < requestedPermCount; j++) {
17714                String permission = ps.pkg.requestedPermissions.get(j);
17715                BasePermission bp = mSettings.mPermissions.get(permission);
17716                if (bp != null) {
17717                    usedPermissions.add(permission);
17718                }
17719            }
17720        }
17721
17722        PermissionsState permissionsState = su.getPermissionsState();
17723        // Prune install permissions
17724        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17725        final int installPermCount = installPermStates.size();
17726        for (int i = installPermCount - 1; i >= 0;  i--) {
17727            PermissionState permissionState = installPermStates.get(i);
17728            if (!usedPermissions.contains(permissionState.getName())) {
17729                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17730                if (bp != null) {
17731                    permissionsState.revokeInstallPermission(bp);
17732                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17733                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17734                }
17735            }
17736        }
17737
17738        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17739
17740        // Prune runtime permissions
17741        for (int userId : allUserIds) {
17742            List<PermissionState> runtimePermStates = permissionsState
17743                    .getRuntimePermissionStates(userId);
17744            final int runtimePermCount = runtimePermStates.size();
17745            for (int i = runtimePermCount - 1; i >= 0; i--) {
17746                PermissionState permissionState = runtimePermStates.get(i);
17747                if (!usedPermissions.contains(permissionState.getName())) {
17748                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17749                    if (bp != null) {
17750                        permissionsState.revokeRuntimePermission(bp, userId);
17751                        permissionsState.updatePermissionFlags(bp, userId,
17752                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17753                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17754                                runtimePermissionChangedUserIds, userId);
17755                    }
17756                }
17757            }
17758        }
17759
17760        return runtimePermissionChangedUserIds;
17761    }
17762
17763    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17764            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17765        // Update the parent package setting
17766        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17767                res, user, installReason);
17768        // Update the child packages setting
17769        final int childCount = (newPackage.childPackages != null)
17770                ? newPackage.childPackages.size() : 0;
17771        for (int i = 0; i < childCount; i++) {
17772            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17773            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17774            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17775                    childRes.origUsers, childRes, user, installReason);
17776        }
17777    }
17778
17779    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17780            String installerPackageName, int[] allUsers, int[] installedForUsers,
17781            PackageInstalledInfo res, UserHandle user, int installReason) {
17782        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17783
17784        String pkgName = newPackage.packageName;
17785        synchronized (mPackages) {
17786            //write settings. the installStatus will be incomplete at this stage.
17787            //note that the new package setting would have already been
17788            //added to mPackages. It hasn't been persisted yet.
17789            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17790            // TODO: Remove this write? It's also written at the end of this method
17791            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17792            mSettings.writeLPr();
17793            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17794        }
17795
17796        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17797        synchronized (mPackages) {
17798            updatePermissionsLPw(newPackage.packageName, newPackage,
17799                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17800                            ? UPDATE_PERMISSIONS_ALL : 0));
17801            // For system-bundled packages, we assume that installing an upgraded version
17802            // of the package implies that the user actually wants to run that new code,
17803            // so we enable the package.
17804            PackageSetting ps = mSettings.mPackages.get(pkgName);
17805            final int userId = user.getIdentifier();
17806            if (ps != null) {
17807                if (isSystemApp(newPackage)) {
17808                    if (DEBUG_INSTALL) {
17809                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17810                    }
17811                    // Enable system package for requested users
17812                    if (res.origUsers != null) {
17813                        for (int origUserId : res.origUsers) {
17814                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17815                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17816                                        origUserId, installerPackageName);
17817                            }
17818                        }
17819                    }
17820                    // Also convey the prior install/uninstall state
17821                    if (allUsers != null && installedForUsers != null) {
17822                        for (int currentUserId : allUsers) {
17823                            final boolean installed = ArrayUtils.contains(
17824                                    installedForUsers, currentUserId);
17825                            if (DEBUG_INSTALL) {
17826                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17827                            }
17828                            ps.setInstalled(installed, currentUserId);
17829                        }
17830                        // these install state changes will be persisted in the
17831                        // upcoming call to mSettings.writeLPr().
17832                    }
17833                }
17834                // It's implied that when a user requests installation, they want the app to be
17835                // installed and enabled.
17836                if (userId != UserHandle.USER_ALL) {
17837                    ps.setInstalled(true, userId);
17838                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17839                }
17840
17841                // When replacing an existing package, preserve the original install reason for all
17842                // users that had the package installed before.
17843                final Set<Integer> previousUserIds = new ArraySet<>();
17844                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17845                    final int installReasonCount = res.removedInfo.installReasons.size();
17846                    for (int i = 0; i < installReasonCount; i++) {
17847                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17848                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17849                        ps.setInstallReason(previousInstallReason, previousUserId);
17850                        previousUserIds.add(previousUserId);
17851                    }
17852                }
17853
17854                // Set install reason for users that are having the package newly installed.
17855                if (userId == UserHandle.USER_ALL) {
17856                    for (int currentUserId : sUserManager.getUserIds()) {
17857                        if (!previousUserIds.contains(currentUserId)) {
17858                            ps.setInstallReason(installReason, currentUserId);
17859                        }
17860                    }
17861                } else if (!previousUserIds.contains(userId)) {
17862                    ps.setInstallReason(installReason, userId);
17863                }
17864                mSettings.writeKernelMappingLPr(ps);
17865            }
17866            res.name = pkgName;
17867            res.uid = newPackage.applicationInfo.uid;
17868            res.pkg = newPackage;
17869            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17870            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17871            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17872            //to update install status
17873            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17874            mSettings.writeLPr();
17875            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17876        }
17877
17878        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17879    }
17880
17881    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17882        try {
17883            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17884            installPackageLI(args, res);
17885        } finally {
17886            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17887        }
17888    }
17889
17890    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17891        final int installFlags = args.installFlags;
17892        final String installerPackageName = args.installerPackageName;
17893        final String volumeUuid = args.volumeUuid;
17894        final File tmpPackageFile = new File(args.getCodePath());
17895        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17896        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17897                || (args.volumeUuid != null));
17898        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17899        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17900        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17901        boolean replace = false;
17902        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17903        if (args.move != null) {
17904            // moving a complete application; perform an initial scan on the new install location
17905            scanFlags |= SCAN_INITIAL;
17906        }
17907        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17908            scanFlags |= SCAN_DONT_KILL_APP;
17909        }
17910        if (instantApp) {
17911            scanFlags |= SCAN_AS_INSTANT_APP;
17912        }
17913        if (fullApp) {
17914            scanFlags |= SCAN_AS_FULL_APP;
17915        }
17916
17917        // Result object to be returned
17918        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17919
17920        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17921
17922        // Sanity check
17923        if (instantApp && (forwardLocked || onExternal)) {
17924            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17925                    + " external=" + onExternal);
17926            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17927            return;
17928        }
17929
17930        // Retrieve PackageSettings and parse package
17931        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17932                | PackageParser.PARSE_ENFORCE_CODE
17933                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17934                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17935                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17936                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17937        PackageParser pp = new PackageParser();
17938        pp.setSeparateProcesses(mSeparateProcesses);
17939        pp.setDisplayMetrics(mMetrics);
17940        pp.setCallback(mPackageParserCallback);
17941
17942        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17943        final PackageParser.Package pkg;
17944        try {
17945            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17946        } catch (PackageParserException e) {
17947            res.setError("Failed parse during installPackageLI", e);
17948            return;
17949        } finally {
17950            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17951        }
17952
17953        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17954        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17955            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17956            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17957                    "Instant app package must target O");
17958            return;
17959        }
17960        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17961            Slog.w(TAG, "Instant app package " + pkg.packageName
17962                    + " does not target targetSandboxVersion 2");
17963            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17964                    "Instant app package must use targetSanboxVersion 2");
17965            return;
17966        }
17967
17968        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17969            // Static shared libraries have synthetic package names
17970            renameStaticSharedLibraryPackage(pkg);
17971
17972            // No static shared libs on external storage
17973            if (onExternal) {
17974                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17975                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17976                        "Packages declaring static-shared libs cannot be updated");
17977                return;
17978            }
17979        }
17980
17981        // If we are installing a clustered package add results for the children
17982        if (pkg.childPackages != null) {
17983            synchronized (mPackages) {
17984                final int childCount = pkg.childPackages.size();
17985                for (int i = 0; i < childCount; i++) {
17986                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17987                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17988                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17989                    childRes.pkg = childPkg;
17990                    childRes.name = childPkg.packageName;
17991                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17992                    if (childPs != null) {
17993                        childRes.origUsers = childPs.queryInstalledUsers(
17994                                sUserManager.getUserIds(), true);
17995                    }
17996                    if ((mPackages.containsKey(childPkg.packageName))) {
17997                        childRes.removedInfo = new PackageRemovedInfo(this);
17998                        childRes.removedInfo.removedPackage = childPkg.packageName;
17999                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18000                    }
18001                    if (res.addedChildPackages == null) {
18002                        res.addedChildPackages = new ArrayMap<>();
18003                    }
18004                    res.addedChildPackages.put(childPkg.packageName, childRes);
18005                }
18006            }
18007        }
18008
18009        // If package doesn't declare API override, mark that we have an install
18010        // time CPU ABI override.
18011        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18012            pkg.cpuAbiOverride = args.abiOverride;
18013        }
18014
18015        String pkgName = res.name = pkg.packageName;
18016        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18017            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18018                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18019                return;
18020            }
18021        }
18022
18023        try {
18024            // either use what we've been given or parse directly from the APK
18025            if (args.certificates != null) {
18026                try {
18027                    PackageParser.populateCertificates(pkg, args.certificates);
18028                } catch (PackageParserException e) {
18029                    // there was something wrong with the certificates we were given;
18030                    // try to pull them from the APK
18031                    PackageParser.collectCertificates(pkg, parseFlags);
18032                }
18033            } else {
18034                PackageParser.collectCertificates(pkg, parseFlags);
18035            }
18036        } catch (PackageParserException e) {
18037            res.setError("Failed collect during installPackageLI", e);
18038            return;
18039        }
18040
18041        // Get rid of all references to package scan path via parser.
18042        pp = null;
18043        String oldCodePath = null;
18044        boolean systemApp = false;
18045        synchronized (mPackages) {
18046            // Check if installing already existing package
18047            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18048                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18049                if (pkg.mOriginalPackages != null
18050                        && pkg.mOriginalPackages.contains(oldName)
18051                        && mPackages.containsKey(oldName)) {
18052                    // This package is derived from an original package,
18053                    // and this device has been updating from that original
18054                    // name.  We must continue using the original name, so
18055                    // rename the new package here.
18056                    pkg.setPackageName(oldName);
18057                    pkgName = pkg.packageName;
18058                    replace = true;
18059                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18060                            + oldName + " pkgName=" + pkgName);
18061                } else if (mPackages.containsKey(pkgName)) {
18062                    // This package, under its official name, already exists
18063                    // on the device; we should replace it.
18064                    replace = true;
18065                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18066                }
18067
18068                // Child packages are installed through the parent package
18069                if (pkg.parentPackage != null) {
18070                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18071                            "Package " + pkg.packageName + " is child of package "
18072                                    + pkg.parentPackage.parentPackage + ". Child packages "
18073                                    + "can be updated only through the parent package.");
18074                    return;
18075                }
18076
18077                if (replace) {
18078                    // Prevent apps opting out from runtime permissions
18079                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18080                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18081                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18082                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18083                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18084                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18085                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18086                                        + " doesn't support runtime permissions but the old"
18087                                        + " target SDK " + oldTargetSdk + " does.");
18088                        return;
18089                    }
18090                    // Prevent apps from downgrading their targetSandbox.
18091                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18092                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18093                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18094                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18095                                "Package " + pkg.packageName + " new target sandbox "
18096                                + newTargetSandbox + " is incompatible with the previous value of"
18097                                + oldTargetSandbox + ".");
18098                        return;
18099                    }
18100
18101                    // Prevent installing of child packages
18102                    if (oldPackage.parentPackage != null) {
18103                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18104                                "Package " + pkg.packageName + " is child of package "
18105                                        + oldPackage.parentPackage + ". Child packages "
18106                                        + "can be updated only through the parent package.");
18107                        return;
18108                    }
18109                }
18110            }
18111
18112            PackageSetting ps = mSettings.mPackages.get(pkgName);
18113            if (ps != null) {
18114                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18115
18116                // Static shared libs have same package with different versions where
18117                // we internally use a synthetic package name to allow multiple versions
18118                // of the same package, therefore we need to compare signatures against
18119                // the package setting for the latest library version.
18120                PackageSetting signatureCheckPs = ps;
18121                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18122                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18123                    if (libraryEntry != null) {
18124                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18125                    }
18126                }
18127
18128                // Quick sanity check that we're signed correctly if updating;
18129                // we'll check this again later when scanning, but we want to
18130                // bail early here before tripping over redefined permissions.
18131                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18132                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18133                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18134                                + pkg.packageName + " upgrade keys do not match the "
18135                                + "previously installed version");
18136                        return;
18137                    }
18138                } else {
18139                    try {
18140                        verifySignaturesLP(signatureCheckPs, pkg);
18141                    } catch (PackageManagerException e) {
18142                        res.setError(e.error, e.getMessage());
18143                        return;
18144                    }
18145                }
18146
18147                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18148                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18149                    systemApp = (ps.pkg.applicationInfo.flags &
18150                            ApplicationInfo.FLAG_SYSTEM) != 0;
18151                }
18152                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18153            }
18154
18155            int N = pkg.permissions.size();
18156            for (int i = N-1; i >= 0; i--) {
18157                PackageParser.Permission perm = pkg.permissions.get(i);
18158                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18159
18160                // Don't allow anyone but the system to define ephemeral permissions.
18161                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18162                        && !systemApp) {
18163                    Slog.w(TAG, "Non-System package " + pkg.packageName
18164                            + " attempting to delcare ephemeral permission "
18165                            + perm.info.name + "; Removing ephemeral.");
18166                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18167                }
18168                // Check whether the newly-scanned package wants to define an already-defined perm
18169                if (bp != null) {
18170                    // If the defining package is signed with our cert, it's okay.  This
18171                    // also includes the "updating the same package" case, of course.
18172                    // "updating same package" could also involve key-rotation.
18173                    final boolean sigsOk;
18174                    if (bp.sourcePackage.equals(pkg.packageName)
18175                            && (bp.packageSetting instanceof PackageSetting)
18176                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18177                                    scanFlags))) {
18178                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18179                    } else {
18180                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18181                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18182                    }
18183                    if (!sigsOk) {
18184                        // If the owning package is the system itself, we log but allow
18185                        // install to proceed; we fail the install on all other permission
18186                        // redefinitions.
18187                        if (!bp.sourcePackage.equals("android")) {
18188                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18189                                    + pkg.packageName + " attempting to redeclare permission "
18190                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18191                            res.origPermission = perm.info.name;
18192                            res.origPackage = bp.sourcePackage;
18193                            return;
18194                        } else {
18195                            Slog.w(TAG, "Package " + pkg.packageName
18196                                    + " attempting to redeclare system permission "
18197                                    + perm.info.name + "; ignoring new declaration");
18198                            pkg.permissions.remove(i);
18199                        }
18200                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18201                        // Prevent apps to change protection level to dangerous from any other
18202                        // type as this would allow a privilege escalation where an app adds a
18203                        // normal/signature permission in other app's group and later redefines
18204                        // it as dangerous leading to the group auto-grant.
18205                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18206                                == PermissionInfo.PROTECTION_DANGEROUS) {
18207                            if (bp != null && !bp.isRuntime()) {
18208                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18209                                        + "non-runtime permission " + perm.info.name
18210                                        + " to runtime; keeping old protection level");
18211                                perm.info.protectionLevel = bp.protectionLevel;
18212                            }
18213                        }
18214                    }
18215                }
18216            }
18217        }
18218
18219        if (systemApp) {
18220            if (onExternal) {
18221                // Abort update; system app can't be replaced with app on sdcard
18222                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18223                        "Cannot install updates to system apps on sdcard");
18224                return;
18225            } else if (instantApp) {
18226                // Abort update; system app can't be replaced with an instant app
18227                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18228                        "Cannot update a system app with an instant app");
18229                return;
18230            }
18231        }
18232
18233        if (args.move != null) {
18234            // We did an in-place move, so dex is ready to roll
18235            scanFlags |= SCAN_NO_DEX;
18236            scanFlags |= SCAN_MOVE;
18237
18238            synchronized (mPackages) {
18239                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18240                if (ps == null) {
18241                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18242                            "Missing settings for moved package " + pkgName);
18243                }
18244
18245                // We moved the entire application as-is, so bring over the
18246                // previously derived ABI information.
18247                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18248                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18249            }
18250
18251        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18252            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18253            scanFlags |= SCAN_NO_DEX;
18254
18255            try {
18256                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18257                    args.abiOverride : pkg.cpuAbiOverride);
18258                final boolean extractNativeLibs = !pkg.isLibrary();
18259                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18260                        extractNativeLibs, mAppLib32InstallDir);
18261            } catch (PackageManagerException pme) {
18262                Slog.e(TAG, "Error deriving application ABI", pme);
18263                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18264                return;
18265            }
18266
18267            // Shared libraries for the package need to be updated.
18268            synchronized (mPackages) {
18269                try {
18270                    updateSharedLibrariesLPr(pkg, null);
18271                } catch (PackageManagerException e) {
18272                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18273                }
18274            }
18275        }
18276
18277        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18278            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18279            return;
18280        }
18281
18282        if (!instantApp) {
18283            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18284        } else {
18285            if (DEBUG_DOMAIN_VERIFICATION) {
18286                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
18287            }
18288        }
18289
18290        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18291                "installPackageLI")) {
18292            if (replace) {
18293                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18294                    // Static libs have a synthetic package name containing the version
18295                    // and cannot be updated as an update would get a new package name,
18296                    // unless this is the exact same version code which is useful for
18297                    // development.
18298                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18299                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18300                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18301                                + "static-shared libs cannot be updated");
18302                        return;
18303                    }
18304                }
18305                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18306                        installerPackageName, res, args.installReason);
18307            } else {
18308                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18309                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18310            }
18311        }
18312
18313        // Check whether we need to dexopt the app.
18314        //
18315        // NOTE: it is IMPORTANT to call dexopt:
18316        //   - after doRename which will sync the package data from PackageParser.Package and its
18317        //     corresponding ApplicationInfo.
18318        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
18319        //     uid of the application (pkg.applicationInfo.uid).
18320        //     This update happens in place!
18321        //
18322        // We only need to dexopt if the package meets ALL of the following conditions:
18323        //   1) it is not forward locked.
18324        //   2) it is not on on an external ASEC container.
18325        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18326        //
18327        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18328        // complete, so we skip this step during installation. Instead, we'll take extra time
18329        // the first time the instant app starts. It's preferred to do it this way to provide
18330        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18331        // middle of running an instant app. The default behaviour can be overridden
18332        // via gservices.
18333        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
18334                && !forwardLocked
18335                && !pkg.applicationInfo.isExternalAsec()
18336                && (!instantApp || Global.getInt(mContext.getContentResolver(),
18337                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18338
18339        if (performDexopt) {
18340            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18341            // Do not run PackageDexOptimizer through the local performDexOpt
18342            // method because `pkg` may not be in `mPackages` yet.
18343            //
18344            // Also, don't fail application installs if the dexopt step fails.
18345            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18346                    REASON_INSTALL,
18347                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
18348            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18349                    null /* instructionSets */,
18350                    getOrCreateCompilerPackageStats(pkg),
18351                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18352                    dexoptOptions);
18353            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18354        }
18355
18356        // Notify BackgroundDexOptService that the package has been changed.
18357        // If this is an update of a package which used to fail to compile,
18358        // BackgroundDexOptService will remove it from its blacklist.
18359        // TODO: Layering violation
18360        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18361
18362        synchronized (mPackages) {
18363            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18364            if (ps != null) {
18365                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18366                ps.setUpdateAvailable(false /*updateAvailable*/);
18367            }
18368
18369            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18370            for (int i = 0; i < childCount; i++) {
18371                PackageParser.Package childPkg = pkg.childPackages.get(i);
18372                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18373                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18374                if (childPs != null) {
18375                    childRes.newUsers = childPs.queryInstalledUsers(
18376                            sUserManager.getUserIds(), true);
18377                }
18378            }
18379
18380            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18381                updateSequenceNumberLP(ps, res.newUsers);
18382                updateInstantAppInstallerLocked(pkgName);
18383            }
18384        }
18385    }
18386
18387    private void startIntentFilterVerifications(int userId, boolean replacing,
18388            PackageParser.Package pkg) {
18389        if (mIntentFilterVerifierComponent == null) {
18390            Slog.w(TAG, "No IntentFilter verification will not be done as "
18391                    + "there is no IntentFilterVerifier available!");
18392            return;
18393        }
18394
18395        final int verifierUid = getPackageUid(
18396                mIntentFilterVerifierComponent.getPackageName(),
18397                MATCH_DEBUG_TRIAGED_MISSING,
18398                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18399
18400        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18401        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18402        mHandler.sendMessage(msg);
18403
18404        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18405        for (int i = 0; i < childCount; i++) {
18406            PackageParser.Package childPkg = pkg.childPackages.get(i);
18407            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18408            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18409            mHandler.sendMessage(msg);
18410        }
18411    }
18412
18413    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18414            PackageParser.Package pkg) {
18415        int size = pkg.activities.size();
18416        if (size == 0) {
18417            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18418                    "No activity, so no need to verify any IntentFilter!");
18419            return;
18420        }
18421
18422        final boolean hasDomainURLs = hasDomainURLs(pkg);
18423        if (!hasDomainURLs) {
18424            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18425                    "No domain URLs, so no need to verify any IntentFilter!");
18426            return;
18427        }
18428
18429        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18430                + " if any IntentFilter from the " + size
18431                + " Activities needs verification ...");
18432
18433        int count = 0;
18434        final String packageName = pkg.packageName;
18435
18436        synchronized (mPackages) {
18437            // If this is a new install and we see that we've already run verification for this
18438            // package, we have nothing to do: it means the state was restored from backup.
18439            if (!replacing) {
18440                IntentFilterVerificationInfo ivi =
18441                        mSettings.getIntentFilterVerificationLPr(packageName);
18442                if (ivi != null) {
18443                    if (DEBUG_DOMAIN_VERIFICATION) {
18444                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18445                                + ivi.getStatusString());
18446                    }
18447                    return;
18448                }
18449            }
18450
18451            // If any filters need to be verified, then all need to be.
18452            boolean needToVerify = false;
18453            for (PackageParser.Activity a : pkg.activities) {
18454                for (ActivityIntentInfo filter : a.intents) {
18455                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18456                        if (DEBUG_DOMAIN_VERIFICATION) {
18457                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18458                        }
18459                        needToVerify = true;
18460                        break;
18461                    }
18462                }
18463            }
18464
18465            if (needToVerify) {
18466                final int verificationId = mIntentFilterVerificationToken++;
18467                for (PackageParser.Activity a : pkg.activities) {
18468                    for (ActivityIntentInfo filter : a.intents) {
18469                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18470                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18471                                    "Verification needed for IntentFilter:" + filter.toString());
18472                            mIntentFilterVerifier.addOneIntentFilterVerification(
18473                                    verifierUid, userId, verificationId, filter, packageName);
18474                            count++;
18475                        }
18476                    }
18477                }
18478            }
18479        }
18480
18481        if (count > 0) {
18482            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18483                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18484                    +  " for userId:" + userId);
18485            mIntentFilterVerifier.startVerifications(userId);
18486        } else {
18487            if (DEBUG_DOMAIN_VERIFICATION) {
18488                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18489            }
18490        }
18491    }
18492
18493    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18494        final ComponentName cn  = filter.activity.getComponentName();
18495        final String packageName = cn.getPackageName();
18496
18497        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18498                packageName);
18499        if (ivi == null) {
18500            return true;
18501        }
18502        int status = ivi.getStatus();
18503        switch (status) {
18504            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18505            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18506                return true;
18507
18508            default:
18509                // Nothing to do
18510                return false;
18511        }
18512    }
18513
18514    private static boolean isMultiArch(ApplicationInfo info) {
18515        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18516    }
18517
18518    private static boolean isExternal(PackageParser.Package pkg) {
18519        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18520    }
18521
18522    private static boolean isExternal(PackageSetting ps) {
18523        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18524    }
18525
18526    private static boolean isSystemApp(PackageParser.Package pkg) {
18527        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18528    }
18529
18530    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18531        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18532    }
18533
18534    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18535        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18536    }
18537
18538    private static boolean isSystemApp(PackageSetting ps) {
18539        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18540    }
18541
18542    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18543        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18544    }
18545
18546    private int packageFlagsToInstallFlags(PackageSetting ps) {
18547        int installFlags = 0;
18548        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18549            // This existing package was an external ASEC install when we have
18550            // the external flag without a UUID
18551            installFlags |= PackageManager.INSTALL_EXTERNAL;
18552        }
18553        if (ps.isForwardLocked()) {
18554            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18555        }
18556        return installFlags;
18557    }
18558
18559    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18560        if (isExternal(pkg)) {
18561            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18562                return StorageManager.UUID_PRIMARY_PHYSICAL;
18563            } else {
18564                return pkg.volumeUuid;
18565            }
18566        } else {
18567            return StorageManager.UUID_PRIVATE_INTERNAL;
18568        }
18569    }
18570
18571    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18572        if (isExternal(pkg)) {
18573            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18574                return mSettings.getExternalVersion();
18575            } else {
18576                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18577            }
18578        } else {
18579            return mSettings.getInternalVersion();
18580        }
18581    }
18582
18583    private void deleteTempPackageFiles() {
18584        final FilenameFilter filter = new FilenameFilter() {
18585            public boolean accept(File dir, String name) {
18586                return name.startsWith("vmdl") && name.endsWith(".tmp");
18587            }
18588        };
18589        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18590            file.delete();
18591        }
18592    }
18593
18594    @Override
18595    public void deletePackageAsUser(String packageName, int versionCode,
18596            IPackageDeleteObserver observer, int userId, int flags) {
18597        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18598                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18599    }
18600
18601    @Override
18602    public void deletePackageVersioned(VersionedPackage versionedPackage,
18603            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18604        final int callingUid = Binder.getCallingUid();
18605        mContext.enforceCallingOrSelfPermission(
18606                android.Manifest.permission.DELETE_PACKAGES, null);
18607        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18608        Preconditions.checkNotNull(versionedPackage);
18609        Preconditions.checkNotNull(observer);
18610        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18611                PackageManager.VERSION_CODE_HIGHEST,
18612                Integer.MAX_VALUE, "versionCode must be >= -1");
18613
18614        final String packageName = versionedPackage.getPackageName();
18615        final int versionCode = versionedPackage.getVersionCode();
18616        final String internalPackageName;
18617        synchronized (mPackages) {
18618            // Normalize package name to handle renamed packages and static libs
18619            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18620                    versionedPackage.getVersionCode());
18621        }
18622
18623        final int uid = Binder.getCallingUid();
18624        if (!isOrphaned(internalPackageName)
18625                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18626            try {
18627                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18628                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18629                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18630                observer.onUserActionRequired(intent);
18631            } catch (RemoteException re) {
18632            }
18633            return;
18634        }
18635        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18636        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18637        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18638            mContext.enforceCallingOrSelfPermission(
18639                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18640                    "deletePackage for user " + userId);
18641        }
18642
18643        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18644            try {
18645                observer.onPackageDeleted(packageName,
18646                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18647            } catch (RemoteException re) {
18648            }
18649            return;
18650        }
18651
18652        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18653            try {
18654                observer.onPackageDeleted(packageName,
18655                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18656            } catch (RemoteException re) {
18657            }
18658            return;
18659        }
18660
18661        if (DEBUG_REMOVE) {
18662            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18663                    + " deleteAllUsers: " + deleteAllUsers + " version="
18664                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18665                    ? "VERSION_CODE_HIGHEST" : versionCode));
18666        }
18667        // Queue up an async operation since the package deletion may take a little while.
18668        mHandler.post(new Runnable() {
18669            public void run() {
18670                mHandler.removeCallbacks(this);
18671                int returnCode;
18672                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18673                boolean doDeletePackage = true;
18674                if (ps != null) {
18675                    final boolean targetIsInstantApp =
18676                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18677                    doDeletePackage = !targetIsInstantApp
18678                            || canViewInstantApps;
18679                }
18680                if (doDeletePackage) {
18681                    if (!deleteAllUsers) {
18682                        returnCode = deletePackageX(internalPackageName, versionCode,
18683                                userId, deleteFlags);
18684                    } else {
18685                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18686                                internalPackageName, users);
18687                        // If nobody is blocking uninstall, proceed with delete for all users
18688                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18689                            returnCode = deletePackageX(internalPackageName, versionCode,
18690                                    userId, deleteFlags);
18691                        } else {
18692                            // Otherwise uninstall individually for users with blockUninstalls=false
18693                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18694                            for (int userId : users) {
18695                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18696                                    returnCode = deletePackageX(internalPackageName, versionCode,
18697                                            userId, userFlags);
18698                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18699                                        Slog.w(TAG, "Package delete failed for user " + userId
18700                                                + ", returnCode " + returnCode);
18701                                    }
18702                                }
18703                            }
18704                            // The app has only been marked uninstalled for certain users.
18705                            // We still need to report that delete was blocked
18706                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18707                        }
18708                    }
18709                } else {
18710                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18711                }
18712                try {
18713                    observer.onPackageDeleted(packageName, returnCode, null);
18714                } catch (RemoteException e) {
18715                    Log.i(TAG, "Observer no longer exists.");
18716                } //end catch
18717            } //end run
18718        });
18719    }
18720
18721    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18722        if (pkg.staticSharedLibName != null) {
18723            return pkg.manifestPackageName;
18724        }
18725        return pkg.packageName;
18726    }
18727
18728    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18729        // Handle renamed packages
18730        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18731        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18732
18733        // Is this a static library?
18734        SparseArray<SharedLibraryEntry> versionedLib =
18735                mStaticLibsByDeclaringPackage.get(packageName);
18736        if (versionedLib == null || versionedLib.size() <= 0) {
18737            return packageName;
18738        }
18739
18740        // Figure out which lib versions the caller can see
18741        SparseIntArray versionsCallerCanSee = null;
18742        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18743        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18744                && callingAppId != Process.ROOT_UID) {
18745            versionsCallerCanSee = new SparseIntArray();
18746            String libName = versionedLib.valueAt(0).info.getName();
18747            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18748            if (uidPackages != null) {
18749                for (String uidPackage : uidPackages) {
18750                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18751                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18752                    if (libIdx >= 0) {
18753                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18754                        versionsCallerCanSee.append(libVersion, libVersion);
18755                    }
18756                }
18757            }
18758        }
18759
18760        // Caller can see nothing - done
18761        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18762            return packageName;
18763        }
18764
18765        // Find the version the caller can see and the app version code
18766        SharedLibraryEntry highestVersion = null;
18767        final int versionCount = versionedLib.size();
18768        for (int i = 0; i < versionCount; i++) {
18769            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18770            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18771                    libEntry.info.getVersion()) < 0) {
18772                continue;
18773            }
18774            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18775            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18776                if (libVersionCode == versionCode) {
18777                    return libEntry.apk;
18778                }
18779            } else if (highestVersion == null) {
18780                highestVersion = libEntry;
18781            } else if (libVersionCode  > highestVersion.info
18782                    .getDeclaringPackage().getVersionCode()) {
18783                highestVersion = libEntry;
18784            }
18785        }
18786
18787        if (highestVersion != null) {
18788            return highestVersion.apk;
18789        }
18790
18791        return packageName;
18792    }
18793
18794    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18795        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18796              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18797            return true;
18798        }
18799        final int callingUserId = UserHandle.getUserId(callingUid);
18800        // If the caller installed the pkgName, then allow it to silently uninstall.
18801        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18802            return true;
18803        }
18804
18805        // Allow package verifier to silently uninstall.
18806        if (mRequiredVerifierPackage != null &&
18807                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18808            return true;
18809        }
18810
18811        // Allow package uninstaller to silently uninstall.
18812        if (mRequiredUninstallerPackage != null &&
18813                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18814            return true;
18815        }
18816
18817        // Allow storage manager to silently uninstall.
18818        if (mStorageManagerPackage != null &&
18819                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18820            return true;
18821        }
18822
18823        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18824        // uninstall for device owner provisioning.
18825        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18826                == PERMISSION_GRANTED) {
18827            return true;
18828        }
18829
18830        return false;
18831    }
18832
18833    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18834        int[] result = EMPTY_INT_ARRAY;
18835        for (int userId : userIds) {
18836            if (getBlockUninstallForUser(packageName, userId)) {
18837                result = ArrayUtils.appendInt(result, userId);
18838            }
18839        }
18840        return result;
18841    }
18842
18843    @Override
18844    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18845        final int callingUid = Binder.getCallingUid();
18846        if (getInstantAppPackageName(callingUid) != null
18847                && !isCallerSameApp(packageName, callingUid)) {
18848            return false;
18849        }
18850        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18851    }
18852
18853    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18854        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18855                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18856        try {
18857            if (dpm != null) {
18858                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18859                        /* callingUserOnly =*/ false);
18860                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18861                        : deviceOwnerComponentName.getPackageName();
18862                // Does the package contains the device owner?
18863                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18864                // this check is probably not needed, since DO should be registered as a device
18865                // admin on some user too. (Original bug for this: b/17657954)
18866                if (packageName.equals(deviceOwnerPackageName)) {
18867                    return true;
18868                }
18869                // Does it contain a device admin for any user?
18870                int[] users;
18871                if (userId == UserHandle.USER_ALL) {
18872                    users = sUserManager.getUserIds();
18873                } else {
18874                    users = new int[]{userId};
18875                }
18876                for (int i = 0; i < users.length; ++i) {
18877                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18878                        return true;
18879                    }
18880                }
18881            }
18882        } catch (RemoteException e) {
18883        }
18884        return false;
18885    }
18886
18887    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18888        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18889    }
18890
18891    /**
18892     *  This method is an internal method that could be get invoked either
18893     *  to delete an installed package or to clean up a failed installation.
18894     *  After deleting an installed package, a broadcast is sent to notify any
18895     *  listeners that the package has been removed. For cleaning up a failed
18896     *  installation, the broadcast is not necessary since the package's
18897     *  installation wouldn't have sent the initial broadcast either
18898     *  The key steps in deleting a package are
18899     *  deleting the package information in internal structures like mPackages,
18900     *  deleting the packages base directories through installd
18901     *  updating mSettings to reflect current status
18902     *  persisting settings for later use
18903     *  sending a broadcast if necessary
18904     */
18905    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18906        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18907        final boolean res;
18908
18909        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18910                ? UserHandle.USER_ALL : userId;
18911
18912        if (isPackageDeviceAdmin(packageName, removeUser)) {
18913            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18914            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18915        }
18916
18917        PackageSetting uninstalledPs = null;
18918        PackageParser.Package pkg = null;
18919
18920        // for the uninstall-updates case and restricted profiles, remember the per-
18921        // user handle installed state
18922        int[] allUsers;
18923        synchronized (mPackages) {
18924            uninstalledPs = mSettings.mPackages.get(packageName);
18925            if (uninstalledPs == null) {
18926                Slog.w(TAG, "Not removing non-existent package " + packageName);
18927                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18928            }
18929
18930            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18931                    && uninstalledPs.versionCode != versionCode) {
18932                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18933                        + uninstalledPs.versionCode + " != " + versionCode);
18934                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18935            }
18936
18937            // Static shared libs can be declared by any package, so let us not
18938            // allow removing a package if it provides a lib others depend on.
18939            pkg = mPackages.get(packageName);
18940
18941            allUsers = sUserManager.getUserIds();
18942
18943            if (pkg != null && pkg.staticSharedLibName != null) {
18944                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18945                        pkg.staticSharedLibVersion);
18946                if (libEntry != null) {
18947                    for (int currUserId : allUsers) {
18948                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18949                            continue;
18950                        }
18951                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18952                                libEntry.info, 0, currUserId);
18953                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18954                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18955                                    + " hosting lib " + libEntry.info.getName() + " version "
18956                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18957                                    + " for user " + currUserId);
18958                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18959                        }
18960                    }
18961                }
18962            }
18963
18964            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18965        }
18966
18967        final int freezeUser;
18968        if (isUpdatedSystemApp(uninstalledPs)
18969                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18970            // We're downgrading a system app, which will apply to all users, so
18971            // freeze them all during the downgrade
18972            freezeUser = UserHandle.USER_ALL;
18973        } else {
18974            freezeUser = removeUser;
18975        }
18976
18977        synchronized (mInstallLock) {
18978            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18979            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18980                    deleteFlags, "deletePackageX")) {
18981                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18982                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18983            }
18984            synchronized (mPackages) {
18985                if (res) {
18986                    if (pkg != null) {
18987                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18988                    }
18989                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18990                    updateInstantAppInstallerLocked(packageName);
18991                }
18992            }
18993        }
18994
18995        if (res) {
18996            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18997            info.sendPackageRemovedBroadcasts(killApp);
18998            info.sendSystemPackageUpdatedBroadcasts();
18999            info.sendSystemPackageAppearedBroadcasts();
19000        }
19001        // Force a gc here.
19002        Runtime.getRuntime().gc();
19003        // Delete the resources here after sending the broadcast to let
19004        // other processes clean up before deleting resources.
19005        if (info.args != null) {
19006            synchronized (mInstallLock) {
19007                info.args.doPostDeleteLI(true);
19008            }
19009        }
19010
19011        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19012    }
19013
19014    static class PackageRemovedInfo {
19015        final PackageSender packageSender;
19016        String removedPackage;
19017        String installerPackageName;
19018        int uid = -1;
19019        int removedAppId = -1;
19020        int[] origUsers;
19021        int[] removedUsers = null;
19022        int[] broadcastUsers = null;
19023        SparseArray<Integer> installReasons;
19024        boolean isRemovedPackageSystemUpdate = false;
19025        boolean isUpdate;
19026        boolean dataRemoved;
19027        boolean removedForAllUsers;
19028        boolean isStaticSharedLib;
19029        // Clean up resources deleted packages.
19030        InstallArgs args = null;
19031        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19032        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19033
19034        PackageRemovedInfo(PackageSender packageSender) {
19035            this.packageSender = packageSender;
19036        }
19037
19038        void sendPackageRemovedBroadcasts(boolean killApp) {
19039            sendPackageRemovedBroadcastInternal(killApp);
19040            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19041            for (int i = 0; i < childCount; i++) {
19042                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19043                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19044            }
19045        }
19046
19047        void sendSystemPackageUpdatedBroadcasts() {
19048            if (isRemovedPackageSystemUpdate) {
19049                sendSystemPackageUpdatedBroadcastsInternal();
19050                final int childCount = (removedChildPackages != null)
19051                        ? removedChildPackages.size() : 0;
19052                for (int i = 0; i < childCount; i++) {
19053                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19054                    if (childInfo.isRemovedPackageSystemUpdate) {
19055                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19056                    }
19057                }
19058            }
19059        }
19060
19061        void sendSystemPackageAppearedBroadcasts() {
19062            final int packageCount = (appearedChildPackages != null)
19063                    ? appearedChildPackages.size() : 0;
19064            for (int i = 0; i < packageCount; i++) {
19065                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19066                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19067                    true, UserHandle.getAppId(installedInfo.uid),
19068                    installedInfo.newUsers);
19069            }
19070        }
19071
19072        private void sendSystemPackageUpdatedBroadcastsInternal() {
19073            Bundle extras = new Bundle(2);
19074            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19075            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19076            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19077                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19078            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19079                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19080            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19081                null, null, 0, removedPackage, null, null);
19082            if (installerPackageName != null) {
19083                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19084                        removedPackage, extras, 0 /*flags*/,
19085                        installerPackageName, null, null);
19086                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19087                        removedPackage, extras, 0 /*flags*/,
19088                        installerPackageName, null, null);
19089            }
19090        }
19091
19092        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19093            // Don't send static shared library removal broadcasts as these
19094            // libs are visible only the the apps that depend on them an one
19095            // cannot remove the library if it has a dependency.
19096            if (isStaticSharedLib) {
19097                return;
19098            }
19099            Bundle extras = new Bundle(2);
19100            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19101            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19102            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19103            if (isUpdate || isRemovedPackageSystemUpdate) {
19104                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19105            }
19106            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19107            if (removedPackage != null) {
19108                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19109                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19110                if (installerPackageName != null) {
19111                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19112                            removedPackage, extras, 0 /*flags*/,
19113                            installerPackageName, null, broadcastUsers);
19114                }
19115                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19116                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19117                        removedPackage, extras,
19118                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19119                        null, null, broadcastUsers);
19120                }
19121            }
19122            if (removedAppId >= 0) {
19123                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19124                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19125                    null, null, broadcastUsers);
19126            }
19127        }
19128
19129        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19130            removedUsers = userIds;
19131            if (removedUsers == null) {
19132                broadcastUsers = null;
19133                return;
19134            }
19135
19136            broadcastUsers = EMPTY_INT_ARRAY;
19137            for (int i = userIds.length - 1; i >= 0; --i) {
19138                final int userId = userIds[i];
19139                if (deletedPackageSetting.getInstantApp(userId)) {
19140                    continue;
19141                }
19142                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19143            }
19144        }
19145    }
19146
19147    /*
19148     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19149     * flag is not set, the data directory is removed as well.
19150     * make sure this flag is set for partially installed apps. If not its meaningless to
19151     * delete a partially installed application.
19152     */
19153    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19154            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19155        String packageName = ps.name;
19156        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19157        // Retrieve object to delete permissions for shared user later on
19158        final PackageParser.Package deletedPkg;
19159        final PackageSetting deletedPs;
19160        // reader
19161        synchronized (mPackages) {
19162            deletedPkg = mPackages.get(packageName);
19163            deletedPs = mSettings.mPackages.get(packageName);
19164            if (outInfo != null) {
19165                outInfo.removedPackage = packageName;
19166                outInfo.installerPackageName = ps.installerPackageName;
19167                outInfo.isStaticSharedLib = deletedPkg != null
19168                        && deletedPkg.staticSharedLibName != null;
19169                outInfo.populateUsers(deletedPs == null ? null
19170                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19171            }
19172        }
19173
19174        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19175
19176        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19177            final PackageParser.Package resolvedPkg;
19178            if (deletedPkg != null) {
19179                resolvedPkg = deletedPkg;
19180            } else {
19181                // We don't have a parsed package when it lives on an ejected
19182                // adopted storage device, so fake something together
19183                resolvedPkg = new PackageParser.Package(ps.name);
19184                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19185            }
19186            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19187                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19188            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19189            if (outInfo != null) {
19190                outInfo.dataRemoved = true;
19191            }
19192            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19193        }
19194
19195        int removedAppId = -1;
19196
19197        // writer
19198        synchronized (mPackages) {
19199            boolean installedStateChanged = false;
19200            if (deletedPs != null) {
19201                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19202                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19203                    clearDefaultBrowserIfNeeded(packageName);
19204                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19205                    removedAppId = mSettings.removePackageLPw(packageName);
19206                    if (outInfo != null) {
19207                        outInfo.removedAppId = removedAppId;
19208                    }
19209                    updatePermissionsLPw(deletedPs.name, null, 0);
19210                    if (deletedPs.sharedUser != null) {
19211                        // Remove permissions associated with package. Since runtime
19212                        // permissions are per user we have to kill the removed package
19213                        // or packages running under the shared user of the removed
19214                        // package if revoking the permissions requested only by the removed
19215                        // package is successful and this causes a change in gids.
19216                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19217                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19218                                    userId);
19219                            if (userIdToKill == UserHandle.USER_ALL
19220                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19221                                // If gids changed for this user, kill all affected packages.
19222                                mHandler.post(new Runnable() {
19223                                    @Override
19224                                    public void run() {
19225                                        // This has to happen with no lock held.
19226                                        killApplication(deletedPs.name, deletedPs.appId,
19227                                                KILL_APP_REASON_GIDS_CHANGED);
19228                                    }
19229                                });
19230                                break;
19231                            }
19232                        }
19233                    }
19234                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19235                }
19236                // make sure to preserve per-user disabled state if this removal was just
19237                // a downgrade of a system app to the factory package
19238                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19239                    if (DEBUG_REMOVE) {
19240                        Slog.d(TAG, "Propagating install state across downgrade");
19241                    }
19242                    for (int userId : allUserHandles) {
19243                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19244                        if (DEBUG_REMOVE) {
19245                            Slog.d(TAG, "    user " + userId + " => " + installed);
19246                        }
19247                        if (installed != ps.getInstalled(userId)) {
19248                            installedStateChanged = true;
19249                        }
19250                        ps.setInstalled(installed, userId);
19251                    }
19252                }
19253            }
19254            // can downgrade to reader
19255            if (writeSettings) {
19256                // Save settings now
19257                mSettings.writeLPr();
19258            }
19259            if (installedStateChanged) {
19260                mSettings.writeKernelMappingLPr(ps);
19261            }
19262        }
19263        if (removedAppId != -1) {
19264            // A user ID was deleted here. Go through all users and remove it
19265            // from KeyStore.
19266            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19267        }
19268    }
19269
19270    static boolean locationIsPrivileged(File path) {
19271        try {
19272            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19273                    .getCanonicalPath();
19274            return path.getCanonicalPath().startsWith(privilegedAppDir);
19275        } catch (IOException e) {
19276            Slog.e(TAG, "Unable to access code path " + path);
19277        }
19278        return false;
19279    }
19280
19281    /*
19282     * Tries to delete system package.
19283     */
19284    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19285            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19286            boolean writeSettings) {
19287        if (deletedPs.parentPackageName != null) {
19288            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19289            return false;
19290        }
19291
19292        final boolean applyUserRestrictions
19293                = (allUserHandles != null) && (outInfo.origUsers != null);
19294        final PackageSetting disabledPs;
19295        // Confirm if the system package has been updated
19296        // An updated system app can be deleted. This will also have to restore
19297        // the system pkg from system partition
19298        // reader
19299        synchronized (mPackages) {
19300            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19301        }
19302
19303        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19304                + " disabledPs=" + disabledPs);
19305
19306        if (disabledPs == null) {
19307            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19308            return false;
19309        } else if (DEBUG_REMOVE) {
19310            Slog.d(TAG, "Deleting system pkg from data partition");
19311        }
19312
19313        if (DEBUG_REMOVE) {
19314            if (applyUserRestrictions) {
19315                Slog.d(TAG, "Remembering install states:");
19316                for (int userId : allUserHandles) {
19317                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19318                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19319                }
19320            }
19321        }
19322
19323        // Delete the updated package
19324        outInfo.isRemovedPackageSystemUpdate = true;
19325        if (outInfo.removedChildPackages != null) {
19326            final int childCount = (deletedPs.childPackageNames != null)
19327                    ? deletedPs.childPackageNames.size() : 0;
19328            for (int i = 0; i < childCount; i++) {
19329                String childPackageName = deletedPs.childPackageNames.get(i);
19330                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19331                        .contains(childPackageName)) {
19332                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19333                            childPackageName);
19334                    if (childInfo != null) {
19335                        childInfo.isRemovedPackageSystemUpdate = true;
19336                    }
19337                }
19338            }
19339        }
19340
19341        if (disabledPs.versionCode < deletedPs.versionCode) {
19342            // Delete data for downgrades
19343            flags &= ~PackageManager.DELETE_KEEP_DATA;
19344        } else {
19345            // Preserve data by setting flag
19346            flags |= PackageManager.DELETE_KEEP_DATA;
19347        }
19348
19349        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19350                outInfo, writeSettings, disabledPs.pkg);
19351        if (!ret) {
19352            return false;
19353        }
19354
19355        // writer
19356        synchronized (mPackages) {
19357            // Reinstate the old system package
19358            enableSystemPackageLPw(disabledPs.pkg);
19359            // Remove any native libraries from the upgraded package.
19360            removeNativeBinariesLI(deletedPs);
19361        }
19362
19363        // Install the system package
19364        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19365        int parseFlags = mDefParseFlags
19366                | PackageParser.PARSE_MUST_BE_APK
19367                | PackageParser.PARSE_IS_SYSTEM
19368                | PackageParser.PARSE_IS_SYSTEM_DIR;
19369        if (locationIsPrivileged(disabledPs.codePath)) {
19370            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19371        }
19372
19373        final PackageParser.Package newPkg;
19374        try {
19375            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19376                0 /* currentTime */, null);
19377        } catch (PackageManagerException e) {
19378            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19379                    + e.getMessage());
19380            return false;
19381        }
19382
19383        try {
19384            // update shared libraries for the newly re-installed system package
19385            updateSharedLibrariesLPr(newPkg, null);
19386        } catch (PackageManagerException e) {
19387            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19388        }
19389
19390        prepareAppDataAfterInstallLIF(newPkg);
19391
19392        // writer
19393        synchronized (mPackages) {
19394            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19395
19396            // Propagate the permissions state as we do not want to drop on the floor
19397            // runtime permissions. The update permissions method below will take
19398            // care of removing obsolete permissions and grant install permissions.
19399            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19400            updatePermissionsLPw(newPkg.packageName, newPkg,
19401                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19402
19403            if (applyUserRestrictions) {
19404                boolean installedStateChanged = false;
19405                if (DEBUG_REMOVE) {
19406                    Slog.d(TAG, "Propagating install state across reinstall");
19407                }
19408                for (int userId : allUserHandles) {
19409                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19410                    if (DEBUG_REMOVE) {
19411                        Slog.d(TAG, "    user " + userId + " => " + installed);
19412                    }
19413                    if (installed != ps.getInstalled(userId)) {
19414                        installedStateChanged = true;
19415                    }
19416                    ps.setInstalled(installed, userId);
19417
19418                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19419                }
19420                // Regardless of writeSettings we need to ensure that this restriction
19421                // state propagation is persisted
19422                mSettings.writeAllUsersPackageRestrictionsLPr();
19423                if (installedStateChanged) {
19424                    mSettings.writeKernelMappingLPr(ps);
19425                }
19426            }
19427            // can downgrade to reader here
19428            if (writeSettings) {
19429                mSettings.writeLPr();
19430            }
19431        }
19432        return true;
19433    }
19434
19435    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19436            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19437            PackageRemovedInfo outInfo, boolean writeSettings,
19438            PackageParser.Package replacingPackage) {
19439        synchronized (mPackages) {
19440            if (outInfo != null) {
19441                outInfo.uid = ps.appId;
19442            }
19443
19444            if (outInfo != null && outInfo.removedChildPackages != null) {
19445                final int childCount = (ps.childPackageNames != null)
19446                        ? ps.childPackageNames.size() : 0;
19447                for (int i = 0; i < childCount; i++) {
19448                    String childPackageName = ps.childPackageNames.get(i);
19449                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19450                    if (childPs == null) {
19451                        return false;
19452                    }
19453                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19454                            childPackageName);
19455                    if (childInfo != null) {
19456                        childInfo.uid = childPs.appId;
19457                    }
19458                }
19459            }
19460        }
19461
19462        // Delete package data from internal structures and also remove data if flag is set
19463        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19464
19465        // Delete the child packages data
19466        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19467        for (int i = 0; i < childCount; i++) {
19468            PackageSetting childPs;
19469            synchronized (mPackages) {
19470                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19471            }
19472            if (childPs != null) {
19473                PackageRemovedInfo childOutInfo = (outInfo != null
19474                        && outInfo.removedChildPackages != null)
19475                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19476                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19477                        && (replacingPackage != null
19478                        && !replacingPackage.hasChildPackage(childPs.name))
19479                        ? flags & ~DELETE_KEEP_DATA : flags;
19480                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19481                        deleteFlags, writeSettings);
19482            }
19483        }
19484
19485        // Delete application code and resources only for parent packages
19486        if (ps.parentPackageName == null) {
19487            if (deleteCodeAndResources && (outInfo != null)) {
19488                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19489                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19490                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19491            }
19492        }
19493
19494        return true;
19495    }
19496
19497    @Override
19498    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19499            int userId) {
19500        mContext.enforceCallingOrSelfPermission(
19501                android.Manifest.permission.DELETE_PACKAGES, null);
19502        synchronized (mPackages) {
19503            // Cannot block uninstall of static shared libs as they are
19504            // considered a part of the using app (emulating static linking).
19505            // Also static libs are installed always on internal storage.
19506            PackageParser.Package pkg = mPackages.get(packageName);
19507            if (pkg != null && pkg.staticSharedLibName != null) {
19508                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19509                        + " providing static shared library: " + pkg.staticSharedLibName);
19510                return false;
19511            }
19512            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19513            mSettings.writePackageRestrictionsLPr(userId);
19514        }
19515        return true;
19516    }
19517
19518    @Override
19519    public boolean getBlockUninstallForUser(String packageName, int userId) {
19520        synchronized (mPackages) {
19521            final PackageSetting ps = mSettings.mPackages.get(packageName);
19522            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19523                return false;
19524            }
19525            return mSettings.getBlockUninstallLPr(userId, packageName);
19526        }
19527    }
19528
19529    @Override
19530    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19531        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19532        synchronized (mPackages) {
19533            PackageSetting ps = mSettings.mPackages.get(packageName);
19534            if (ps == null) {
19535                Log.w(TAG, "Package doesn't exist: " + packageName);
19536                return false;
19537            }
19538            if (systemUserApp) {
19539                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19540            } else {
19541                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19542            }
19543            mSettings.writeLPr();
19544        }
19545        return true;
19546    }
19547
19548    /*
19549     * This method handles package deletion in general
19550     */
19551    private boolean deletePackageLIF(String packageName, UserHandle user,
19552            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19553            PackageRemovedInfo outInfo, boolean writeSettings,
19554            PackageParser.Package replacingPackage) {
19555        if (packageName == null) {
19556            Slog.w(TAG, "Attempt to delete null packageName.");
19557            return false;
19558        }
19559
19560        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19561
19562        PackageSetting ps;
19563        synchronized (mPackages) {
19564            ps = mSettings.mPackages.get(packageName);
19565            if (ps == null) {
19566                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19567                return false;
19568            }
19569
19570            if (ps.parentPackageName != null && (!isSystemApp(ps)
19571                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19572                if (DEBUG_REMOVE) {
19573                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19574                            + ((user == null) ? UserHandle.USER_ALL : user));
19575                }
19576                final int removedUserId = (user != null) ? user.getIdentifier()
19577                        : UserHandle.USER_ALL;
19578                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19579                    return false;
19580                }
19581                markPackageUninstalledForUserLPw(ps, user);
19582                scheduleWritePackageRestrictionsLocked(user);
19583                return true;
19584            }
19585        }
19586
19587        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19588                && user.getIdentifier() != UserHandle.USER_ALL)) {
19589            // The caller is asking that the package only be deleted for a single
19590            // user.  To do this, we just mark its uninstalled state and delete
19591            // its data. If this is a system app, we only allow this to happen if
19592            // they have set the special DELETE_SYSTEM_APP which requests different
19593            // semantics than normal for uninstalling system apps.
19594            markPackageUninstalledForUserLPw(ps, user);
19595
19596            if (!isSystemApp(ps)) {
19597                // Do not uninstall the APK if an app should be cached
19598                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19599                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19600                    // Other user still have this package installed, so all
19601                    // we need to do is clear this user's data and save that
19602                    // it is uninstalled.
19603                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19604                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19605                        return false;
19606                    }
19607                    scheduleWritePackageRestrictionsLocked(user);
19608                    return true;
19609                } else {
19610                    // We need to set it back to 'installed' so the uninstall
19611                    // broadcasts will be sent correctly.
19612                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19613                    ps.setInstalled(true, user.getIdentifier());
19614                    mSettings.writeKernelMappingLPr(ps);
19615                }
19616            } else {
19617                // This is a system app, so we assume that the
19618                // other users still have this package installed, so all
19619                // we need to do is clear this user's data and save that
19620                // it is uninstalled.
19621                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19622                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19623                    return false;
19624                }
19625                scheduleWritePackageRestrictionsLocked(user);
19626                return true;
19627            }
19628        }
19629
19630        // If we are deleting a composite package for all users, keep track
19631        // of result for each child.
19632        if (ps.childPackageNames != null && outInfo != null) {
19633            synchronized (mPackages) {
19634                final int childCount = ps.childPackageNames.size();
19635                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19636                for (int i = 0; i < childCount; i++) {
19637                    String childPackageName = ps.childPackageNames.get(i);
19638                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19639                    childInfo.removedPackage = childPackageName;
19640                    childInfo.installerPackageName = ps.installerPackageName;
19641                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19642                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19643                    if (childPs != null) {
19644                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19645                    }
19646                }
19647            }
19648        }
19649
19650        boolean ret = false;
19651        if (isSystemApp(ps)) {
19652            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19653            // When an updated system application is deleted we delete the existing resources
19654            // as well and fall back to existing code in system partition
19655            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19656        } else {
19657            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19658            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19659                    outInfo, writeSettings, replacingPackage);
19660        }
19661
19662        // Take a note whether we deleted the package for all users
19663        if (outInfo != null) {
19664            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19665            if (outInfo.removedChildPackages != null) {
19666                synchronized (mPackages) {
19667                    final int childCount = outInfo.removedChildPackages.size();
19668                    for (int i = 0; i < childCount; i++) {
19669                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19670                        if (childInfo != null) {
19671                            childInfo.removedForAllUsers = mPackages.get(
19672                                    childInfo.removedPackage) == null;
19673                        }
19674                    }
19675                }
19676            }
19677            // If we uninstalled an update to a system app there may be some
19678            // child packages that appeared as they are declared in the system
19679            // app but were not declared in the update.
19680            if (isSystemApp(ps)) {
19681                synchronized (mPackages) {
19682                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19683                    final int childCount = (updatedPs.childPackageNames != null)
19684                            ? updatedPs.childPackageNames.size() : 0;
19685                    for (int i = 0; i < childCount; i++) {
19686                        String childPackageName = updatedPs.childPackageNames.get(i);
19687                        if (outInfo.removedChildPackages == null
19688                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19689                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19690                            if (childPs == null) {
19691                                continue;
19692                            }
19693                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19694                            installRes.name = childPackageName;
19695                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19696                            installRes.pkg = mPackages.get(childPackageName);
19697                            installRes.uid = childPs.pkg.applicationInfo.uid;
19698                            if (outInfo.appearedChildPackages == null) {
19699                                outInfo.appearedChildPackages = new ArrayMap<>();
19700                            }
19701                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19702                        }
19703                    }
19704                }
19705            }
19706        }
19707
19708        return ret;
19709    }
19710
19711    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19712        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19713                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19714        for (int nextUserId : userIds) {
19715            if (DEBUG_REMOVE) {
19716                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19717            }
19718            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19719                    false /*installed*/,
19720                    true /*stopped*/,
19721                    true /*notLaunched*/,
19722                    false /*hidden*/,
19723                    false /*suspended*/,
19724                    false /*instantApp*/,
19725                    null /*lastDisableAppCaller*/,
19726                    null /*enabledComponents*/,
19727                    null /*disabledComponents*/,
19728                    ps.readUserState(nextUserId).domainVerificationStatus,
19729                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19730        }
19731        mSettings.writeKernelMappingLPr(ps);
19732    }
19733
19734    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19735            PackageRemovedInfo outInfo) {
19736        final PackageParser.Package pkg;
19737        synchronized (mPackages) {
19738            pkg = mPackages.get(ps.name);
19739        }
19740
19741        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19742                : new int[] {userId};
19743        for (int nextUserId : userIds) {
19744            if (DEBUG_REMOVE) {
19745                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19746                        + nextUserId);
19747            }
19748
19749            destroyAppDataLIF(pkg, userId,
19750                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19751            destroyAppProfilesLIF(pkg, userId);
19752            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19753            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19754            schedulePackageCleaning(ps.name, nextUserId, false);
19755            synchronized (mPackages) {
19756                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19757                    scheduleWritePackageRestrictionsLocked(nextUserId);
19758                }
19759                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19760            }
19761        }
19762
19763        if (outInfo != null) {
19764            outInfo.removedPackage = ps.name;
19765            outInfo.installerPackageName = ps.installerPackageName;
19766            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19767            outInfo.removedAppId = ps.appId;
19768            outInfo.removedUsers = userIds;
19769            outInfo.broadcastUsers = userIds;
19770        }
19771
19772        return true;
19773    }
19774
19775    private final class ClearStorageConnection implements ServiceConnection {
19776        IMediaContainerService mContainerService;
19777
19778        @Override
19779        public void onServiceConnected(ComponentName name, IBinder service) {
19780            synchronized (this) {
19781                mContainerService = IMediaContainerService.Stub
19782                        .asInterface(Binder.allowBlocking(service));
19783                notifyAll();
19784            }
19785        }
19786
19787        @Override
19788        public void onServiceDisconnected(ComponentName name) {
19789        }
19790    }
19791
19792    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19793        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19794
19795        final boolean mounted;
19796        if (Environment.isExternalStorageEmulated()) {
19797            mounted = true;
19798        } else {
19799            final String status = Environment.getExternalStorageState();
19800
19801            mounted = status.equals(Environment.MEDIA_MOUNTED)
19802                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19803        }
19804
19805        if (!mounted) {
19806            return;
19807        }
19808
19809        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19810        int[] users;
19811        if (userId == UserHandle.USER_ALL) {
19812            users = sUserManager.getUserIds();
19813        } else {
19814            users = new int[] { userId };
19815        }
19816        final ClearStorageConnection conn = new ClearStorageConnection();
19817        if (mContext.bindServiceAsUser(
19818                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19819            try {
19820                for (int curUser : users) {
19821                    long timeout = SystemClock.uptimeMillis() + 5000;
19822                    synchronized (conn) {
19823                        long now;
19824                        while (conn.mContainerService == null &&
19825                                (now = SystemClock.uptimeMillis()) < timeout) {
19826                            try {
19827                                conn.wait(timeout - now);
19828                            } catch (InterruptedException e) {
19829                            }
19830                        }
19831                    }
19832                    if (conn.mContainerService == null) {
19833                        return;
19834                    }
19835
19836                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19837                    clearDirectory(conn.mContainerService,
19838                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19839                    if (allData) {
19840                        clearDirectory(conn.mContainerService,
19841                                userEnv.buildExternalStorageAppDataDirs(packageName));
19842                        clearDirectory(conn.mContainerService,
19843                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19844                    }
19845                }
19846            } finally {
19847                mContext.unbindService(conn);
19848            }
19849        }
19850    }
19851
19852    @Override
19853    public void clearApplicationProfileData(String packageName) {
19854        enforceSystemOrRoot("Only the system can clear all profile data");
19855
19856        final PackageParser.Package pkg;
19857        synchronized (mPackages) {
19858            pkg = mPackages.get(packageName);
19859        }
19860
19861        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19862            synchronized (mInstallLock) {
19863                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19864            }
19865        }
19866    }
19867
19868    @Override
19869    public void clearApplicationUserData(final String packageName,
19870            final IPackageDataObserver observer, final int userId) {
19871        mContext.enforceCallingOrSelfPermission(
19872                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19873
19874        final int callingUid = Binder.getCallingUid();
19875        enforceCrossUserPermission(callingUid, userId,
19876                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19877
19878        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19879        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19880            return;
19881        }
19882        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19883            throw new SecurityException("Cannot clear data for a protected package: "
19884                    + packageName);
19885        }
19886        // Queue up an async operation since the package deletion may take a little while.
19887        mHandler.post(new Runnable() {
19888            public void run() {
19889                mHandler.removeCallbacks(this);
19890                final boolean succeeded;
19891                try (PackageFreezer freezer = freezePackage(packageName,
19892                        "clearApplicationUserData")) {
19893                    synchronized (mInstallLock) {
19894                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19895                    }
19896                    clearExternalStorageDataSync(packageName, userId, true);
19897                    synchronized (mPackages) {
19898                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19899                                packageName, userId);
19900                    }
19901                }
19902                if (succeeded) {
19903                    // invoke DeviceStorageMonitor's update method to clear any notifications
19904                    DeviceStorageMonitorInternal dsm = LocalServices
19905                            .getService(DeviceStorageMonitorInternal.class);
19906                    if (dsm != null) {
19907                        dsm.checkMemory();
19908                    }
19909                }
19910                if(observer != null) {
19911                    try {
19912                        observer.onRemoveCompleted(packageName, succeeded);
19913                    } catch (RemoteException e) {
19914                        Log.i(TAG, "Observer no longer exists.");
19915                    }
19916                } //end if observer
19917            } //end run
19918        });
19919    }
19920
19921    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19922        if (packageName == null) {
19923            Slog.w(TAG, "Attempt to delete null packageName.");
19924            return false;
19925        }
19926
19927        // Try finding details about the requested package
19928        PackageParser.Package pkg;
19929        synchronized (mPackages) {
19930            pkg = mPackages.get(packageName);
19931            if (pkg == null) {
19932                final PackageSetting ps = mSettings.mPackages.get(packageName);
19933                if (ps != null) {
19934                    pkg = ps.pkg;
19935                }
19936            }
19937
19938            if (pkg == null) {
19939                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19940                return false;
19941            }
19942
19943            PackageSetting ps = (PackageSetting) pkg.mExtras;
19944            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19945        }
19946
19947        clearAppDataLIF(pkg, userId,
19948                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19949
19950        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19951        removeKeystoreDataIfNeeded(userId, appId);
19952
19953        UserManagerInternal umInternal = getUserManagerInternal();
19954        final int flags;
19955        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19956            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19957        } else if (umInternal.isUserRunning(userId)) {
19958            flags = StorageManager.FLAG_STORAGE_DE;
19959        } else {
19960            flags = 0;
19961        }
19962        prepareAppDataContentsLIF(pkg, userId, flags);
19963
19964        return true;
19965    }
19966
19967    /**
19968     * Reverts user permission state changes (permissions and flags) in
19969     * all packages for a given user.
19970     *
19971     * @param userId The device user for which to do a reset.
19972     */
19973    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19974        final int packageCount = mPackages.size();
19975        for (int i = 0; i < packageCount; i++) {
19976            PackageParser.Package pkg = mPackages.valueAt(i);
19977            PackageSetting ps = (PackageSetting) pkg.mExtras;
19978            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19979        }
19980    }
19981
19982    private void resetNetworkPolicies(int userId) {
19983        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19984    }
19985
19986    /**
19987     * Reverts user permission state changes (permissions and flags).
19988     *
19989     * @param ps The package for which to reset.
19990     * @param userId The device user for which to do a reset.
19991     */
19992    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19993            final PackageSetting ps, final int userId) {
19994        if (ps.pkg == null) {
19995            return;
19996        }
19997
19998        // These are flags that can change base on user actions.
19999        final int userSettableMask = FLAG_PERMISSION_USER_SET
20000                | FLAG_PERMISSION_USER_FIXED
20001                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20002                | FLAG_PERMISSION_REVIEW_REQUIRED;
20003
20004        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20005                | FLAG_PERMISSION_POLICY_FIXED;
20006
20007        boolean writeInstallPermissions = false;
20008        boolean writeRuntimePermissions = false;
20009
20010        final int permissionCount = ps.pkg.requestedPermissions.size();
20011        for (int i = 0; i < permissionCount; i++) {
20012            String permission = ps.pkg.requestedPermissions.get(i);
20013
20014            BasePermission bp = mSettings.mPermissions.get(permission);
20015            if (bp == null) {
20016                continue;
20017            }
20018
20019            // If shared user we just reset the state to which only this app contributed.
20020            if (ps.sharedUser != null) {
20021                boolean used = false;
20022                final int packageCount = ps.sharedUser.packages.size();
20023                for (int j = 0; j < packageCount; j++) {
20024                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20025                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20026                            && pkg.pkg.requestedPermissions.contains(permission)) {
20027                        used = true;
20028                        break;
20029                    }
20030                }
20031                if (used) {
20032                    continue;
20033                }
20034            }
20035
20036            PermissionsState permissionsState = ps.getPermissionsState();
20037
20038            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20039
20040            // Always clear the user settable flags.
20041            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20042                    bp.name) != null;
20043            // If permission review is enabled and this is a legacy app, mark the
20044            // permission as requiring a review as this is the initial state.
20045            int flags = 0;
20046            if (mPermissionReviewRequired
20047                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20048                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20049            }
20050            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20051                if (hasInstallState) {
20052                    writeInstallPermissions = true;
20053                } else {
20054                    writeRuntimePermissions = true;
20055                }
20056            }
20057
20058            // Below is only runtime permission handling.
20059            if (!bp.isRuntime()) {
20060                continue;
20061            }
20062
20063            // Never clobber system or policy.
20064            if ((oldFlags & policyOrSystemFlags) != 0) {
20065                continue;
20066            }
20067
20068            // If this permission was granted by default, make sure it is.
20069            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20070                if (permissionsState.grantRuntimePermission(bp, userId)
20071                        != PERMISSION_OPERATION_FAILURE) {
20072                    writeRuntimePermissions = true;
20073                }
20074            // If permission review is enabled the permissions for a legacy apps
20075            // are represented as constantly granted runtime ones, so don't revoke.
20076            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20077                // Otherwise, reset the permission.
20078                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20079                switch (revokeResult) {
20080                    case PERMISSION_OPERATION_SUCCESS:
20081                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20082                        writeRuntimePermissions = true;
20083                        final int appId = ps.appId;
20084                        mHandler.post(new Runnable() {
20085                            @Override
20086                            public void run() {
20087                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20088                            }
20089                        });
20090                    } break;
20091                }
20092            }
20093        }
20094
20095        // Synchronously write as we are taking permissions away.
20096        if (writeRuntimePermissions) {
20097            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20098        }
20099
20100        // Synchronously write as we are taking permissions away.
20101        if (writeInstallPermissions) {
20102            mSettings.writeLPr();
20103        }
20104    }
20105
20106    /**
20107     * Remove entries from the keystore daemon. Will only remove it if the
20108     * {@code appId} is valid.
20109     */
20110    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20111        if (appId < 0) {
20112            return;
20113        }
20114
20115        final KeyStore keyStore = KeyStore.getInstance();
20116        if (keyStore != null) {
20117            if (userId == UserHandle.USER_ALL) {
20118                for (final int individual : sUserManager.getUserIds()) {
20119                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20120                }
20121            } else {
20122                keyStore.clearUid(UserHandle.getUid(userId, appId));
20123            }
20124        } else {
20125            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20126        }
20127    }
20128
20129    @Override
20130    public void deleteApplicationCacheFiles(final String packageName,
20131            final IPackageDataObserver observer) {
20132        final int userId = UserHandle.getCallingUserId();
20133        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20134    }
20135
20136    @Override
20137    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20138            final IPackageDataObserver observer) {
20139        final int callingUid = Binder.getCallingUid();
20140        mContext.enforceCallingOrSelfPermission(
20141                android.Manifest.permission.DELETE_CACHE_FILES, null);
20142        enforceCrossUserPermission(callingUid, userId,
20143                /* requireFullPermission= */ true, /* checkShell= */ false,
20144                "delete application cache files");
20145        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20146                android.Manifest.permission.ACCESS_INSTANT_APPS);
20147
20148        final PackageParser.Package pkg;
20149        synchronized (mPackages) {
20150            pkg = mPackages.get(packageName);
20151        }
20152
20153        // Queue up an async operation since the package deletion may take a little while.
20154        mHandler.post(new Runnable() {
20155            public void run() {
20156                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20157                boolean doClearData = true;
20158                if (ps != null) {
20159                    final boolean targetIsInstantApp =
20160                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20161                    doClearData = !targetIsInstantApp
20162                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20163                }
20164                if (doClearData) {
20165                    synchronized (mInstallLock) {
20166                        final int flags = StorageManager.FLAG_STORAGE_DE
20167                                | StorageManager.FLAG_STORAGE_CE;
20168                        // We're only clearing cache files, so we don't care if the
20169                        // app is unfrozen and still able to run
20170                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20171                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20172                    }
20173                    clearExternalStorageDataSync(packageName, userId, false);
20174                }
20175                if (observer != null) {
20176                    try {
20177                        observer.onRemoveCompleted(packageName, true);
20178                    } catch (RemoteException e) {
20179                        Log.i(TAG, "Observer no longer exists.");
20180                    }
20181                }
20182            }
20183        });
20184    }
20185
20186    @Override
20187    public void getPackageSizeInfo(final String packageName, int userHandle,
20188            final IPackageStatsObserver observer) {
20189        throw new UnsupportedOperationException(
20190                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20191    }
20192
20193    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20194        final PackageSetting ps;
20195        synchronized (mPackages) {
20196            ps = mSettings.mPackages.get(packageName);
20197            if (ps == null) {
20198                Slog.w(TAG, "Failed to find settings for " + packageName);
20199                return false;
20200            }
20201        }
20202
20203        final String[] packageNames = { packageName };
20204        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20205        final String[] codePaths = { ps.codePathString };
20206
20207        try {
20208            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20209                    ps.appId, ceDataInodes, codePaths, stats);
20210
20211            // For now, ignore code size of packages on system partition
20212            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20213                stats.codeSize = 0;
20214            }
20215
20216            // External clients expect these to be tracked separately
20217            stats.dataSize -= stats.cacheSize;
20218
20219        } catch (InstallerException e) {
20220            Slog.w(TAG, String.valueOf(e));
20221            return false;
20222        }
20223
20224        return true;
20225    }
20226
20227    private int getUidTargetSdkVersionLockedLPr(int uid) {
20228        Object obj = mSettings.getUserIdLPr(uid);
20229        if (obj instanceof SharedUserSetting) {
20230            final SharedUserSetting sus = (SharedUserSetting) obj;
20231            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20232            final Iterator<PackageSetting> it = sus.packages.iterator();
20233            while (it.hasNext()) {
20234                final PackageSetting ps = it.next();
20235                if (ps.pkg != null) {
20236                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20237                    if (v < vers) vers = v;
20238                }
20239            }
20240            return vers;
20241        } else if (obj instanceof PackageSetting) {
20242            final PackageSetting ps = (PackageSetting) obj;
20243            if (ps.pkg != null) {
20244                return ps.pkg.applicationInfo.targetSdkVersion;
20245            }
20246        }
20247        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20248    }
20249
20250    @Override
20251    public void addPreferredActivity(IntentFilter filter, int match,
20252            ComponentName[] set, ComponentName activity, int userId) {
20253        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20254                "Adding preferred");
20255    }
20256
20257    private void addPreferredActivityInternal(IntentFilter filter, int match,
20258            ComponentName[] set, ComponentName activity, boolean always, int userId,
20259            String opname) {
20260        // writer
20261        int callingUid = Binder.getCallingUid();
20262        enforceCrossUserPermission(callingUid, userId,
20263                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20264        if (filter.countActions() == 0) {
20265            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20266            return;
20267        }
20268        synchronized (mPackages) {
20269            if (mContext.checkCallingOrSelfPermission(
20270                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20271                    != PackageManager.PERMISSION_GRANTED) {
20272                if (getUidTargetSdkVersionLockedLPr(callingUid)
20273                        < Build.VERSION_CODES.FROYO) {
20274                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20275                            + callingUid);
20276                    return;
20277                }
20278                mContext.enforceCallingOrSelfPermission(
20279                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20280            }
20281
20282            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20283            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20284                    + userId + ":");
20285            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20286            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20287            scheduleWritePackageRestrictionsLocked(userId);
20288            postPreferredActivityChangedBroadcast(userId);
20289        }
20290    }
20291
20292    private void postPreferredActivityChangedBroadcast(int userId) {
20293        mHandler.post(() -> {
20294            final IActivityManager am = ActivityManager.getService();
20295            if (am == null) {
20296                return;
20297            }
20298
20299            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20300            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20301            try {
20302                am.broadcastIntent(null, intent, null, null,
20303                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20304                        null, false, false, userId);
20305            } catch (RemoteException e) {
20306            }
20307        });
20308    }
20309
20310    @Override
20311    public void replacePreferredActivity(IntentFilter filter, int match,
20312            ComponentName[] set, ComponentName activity, int userId) {
20313        if (filter.countActions() != 1) {
20314            throw new IllegalArgumentException(
20315                    "replacePreferredActivity expects filter to have only 1 action.");
20316        }
20317        if (filter.countDataAuthorities() != 0
20318                || filter.countDataPaths() != 0
20319                || filter.countDataSchemes() > 1
20320                || filter.countDataTypes() != 0) {
20321            throw new IllegalArgumentException(
20322                    "replacePreferredActivity expects filter to have no data authorities, " +
20323                    "paths, or types; and at most one scheme.");
20324        }
20325
20326        final int callingUid = Binder.getCallingUid();
20327        enforceCrossUserPermission(callingUid, userId,
20328                true /* requireFullPermission */, false /* checkShell */,
20329                "replace preferred activity");
20330        synchronized (mPackages) {
20331            if (mContext.checkCallingOrSelfPermission(
20332                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20333                    != PackageManager.PERMISSION_GRANTED) {
20334                if (getUidTargetSdkVersionLockedLPr(callingUid)
20335                        < Build.VERSION_CODES.FROYO) {
20336                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20337                            + Binder.getCallingUid());
20338                    return;
20339                }
20340                mContext.enforceCallingOrSelfPermission(
20341                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20342            }
20343
20344            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20345            if (pir != null) {
20346                // Get all of the existing entries that exactly match this filter.
20347                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20348                if (existing != null && existing.size() == 1) {
20349                    PreferredActivity cur = existing.get(0);
20350                    if (DEBUG_PREFERRED) {
20351                        Slog.i(TAG, "Checking replace of preferred:");
20352                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20353                        if (!cur.mPref.mAlways) {
20354                            Slog.i(TAG, "  -- CUR; not mAlways!");
20355                        } else {
20356                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20357                            Slog.i(TAG, "  -- CUR: mSet="
20358                                    + Arrays.toString(cur.mPref.mSetComponents));
20359                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20360                            Slog.i(TAG, "  -- NEW: mMatch="
20361                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20362                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20363                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20364                        }
20365                    }
20366                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20367                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20368                            && cur.mPref.sameSet(set)) {
20369                        // Setting the preferred activity to what it happens to be already
20370                        if (DEBUG_PREFERRED) {
20371                            Slog.i(TAG, "Replacing with same preferred activity "
20372                                    + cur.mPref.mShortComponent + " for user "
20373                                    + userId + ":");
20374                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20375                        }
20376                        return;
20377                    }
20378                }
20379
20380                if (existing != null) {
20381                    if (DEBUG_PREFERRED) {
20382                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20383                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20384                    }
20385                    for (int i = 0; i < existing.size(); i++) {
20386                        PreferredActivity pa = existing.get(i);
20387                        if (DEBUG_PREFERRED) {
20388                            Slog.i(TAG, "Removing existing preferred activity "
20389                                    + pa.mPref.mComponent + ":");
20390                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20391                        }
20392                        pir.removeFilter(pa);
20393                    }
20394                }
20395            }
20396            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20397                    "Replacing preferred");
20398        }
20399    }
20400
20401    @Override
20402    public void clearPackagePreferredActivities(String packageName) {
20403        final int callingUid = Binder.getCallingUid();
20404        if (getInstantAppPackageName(callingUid) != null) {
20405            return;
20406        }
20407        // writer
20408        synchronized (mPackages) {
20409            PackageParser.Package pkg = mPackages.get(packageName);
20410            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20411                if (mContext.checkCallingOrSelfPermission(
20412                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20413                        != PackageManager.PERMISSION_GRANTED) {
20414                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20415                            < Build.VERSION_CODES.FROYO) {
20416                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20417                                + callingUid);
20418                        return;
20419                    }
20420                    mContext.enforceCallingOrSelfPermission(
20421                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20422                }
20423            }
20424            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20425            if (ps != null
20426                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20427                return;
20428            }
20429            int user = UserHandle.getCallingUserId();
20430            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20431                scheduleWritePackageRestrictionsLocked(user);
20432            }
20433        }
20434    }
20435
20436    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20437    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20438        ArrayList<PreferredActivity> removed = null;
20439        boolean changed = false;
20440        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20441            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20442            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20443            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20444                continue;
20445            }
20446            Iterator<PreferredActivity> it = pir.filterIterator();
20447            while (it.hasNext()) {
20448                PreferredActivity pa = it.next();
20449                // Mark entry for removal only if it matches the package name
20450                // and the entry is of type "always".
20451                if (packageName == null ||
20452                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20453                                && pa.mPref.mAlways)) {
20454                    if (removed == null) {
20455                        removed = new ArrayList<PreferredActivity>();
20456                    }
20457                    removed.add(pa);
20458                }
20459            }
20460            if (removed != null) {
20461                for (int j=0; j<removed.size(); j++) {
20462                    PreferredActivity pa = removed.get(j);
20463                    pir.removeFilter(pa);
20464                }
20465                changed = true;
20466            }
20467        }
20468        if (changed) {
20469            postPreferredActivityChangedBroadcast(userId);
20470        }
20471        return changed;
20472    }
20473
20474    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20475    private void clearIntentFilterVerificationsLPw(int userId) {
20476        final int packageCount = mPackages.size();
20477        for (int i = 0; i < packageCount; i++) {
20478            PackageParser.Package pkg = mPackages.valueAt(i);
20479            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20480        }
20481    }
20482
20483    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20484    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20485        if (userId == UserHandle.USER_ALL) {
20486            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20487                    sUserManager.getUserIds())) {
20488                for (int oneUserId : sUserManager.getUserIds()) {
20489                    scheduleWritePackageRestrictionsLocked(oneUserId);
20490                }
20491            }
20492        } else {
20493            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20494                scheduleWritePackageRestrictionsLocked(userId);
20495            }
20496        }
20497    }
20498
20499    /** Clears state for all users, and touches intent filter verification policy */
20500    void clearDefaultBrowserIfNeeded(String packageName) {
20501        for (int oneUserId : sUserManager.getUserIds()) {
20502            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20503        }
20504    }
20505
20506    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20507        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20508        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20509            if (packageName.equals(defaultBrowserPackageName)) {
20510                setDefaultBrowserPackageName(null, userId);
20511            }
20512        }
20513    }
20514
20515    @Override
20516    public void resetApplicationPreferences(int userId) {
20517        mContext.enforceCallingOrSelfPermission(
20518                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20519        final long identity = Binder.clearCallingIdentity();
20520        // writer
20521        try {
20522            synchronized (mPackages) {
20523                clearPackagePreferredActivitiesLPw(null, userId);
20524                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20525                // TODO: We have to reset the default SMS and Phone. This requires
20526                // significant refactoring to keep all default apps in the package
20527                // manager (cleaner but more work) or have the services provide
20528                // callbacks to the package manager to request a default app reset.
20529                applyFactoryDefaultBrowserLPw(userId);
20530                clearIntentFilterVerificationsLPw(userId);
20531                primeDomainVerificationsLPw(userId);
20532                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20533                scheduleWritePackageRestrictionsLocked(userId);
20534            }
20535            resetNetworkPolicies(userId);
20536        } finally {
20537            Binder.restoreCallingIdentity(identity);
20538        }
20539    }
20540
20541    @Override
20542    public int getPreferredActivities(List<IntentFilter> outFilters,
20543            List<ComponentName> outActivities, String packageName) {
20544        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20545            return 0;
20546        }
20547        int num = 0;
20548        final int userId = UserHandle.getCallingUserId();
20549        // reader
20550        synchronized (mPackages) {
20551            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20552            if (pir != null) {
20553                final Iterator<PreferredActivity> it = pir.filterIterator();
20554                while (it.hasNext()) {
20555                    final PreferredActivity pa = it.next();
20556                    if (packageName == null
20557                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20558                                    && pa.mPref.mAlways)) {
20559                        if (outFilters != null) {
20560                            outFilters.add(new IntentFilter(pa));
20561                        }
20562                        if (outActivities != null) {
20563                            outActivities.add(pa.mPref.mComponent);
20564                        }
20565                    }
20566                }
20567            }
20568        }
20569
20570        return num;
20571    }
20572
20573    @Override
20574    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20575            int userId) {
20576        int callingUid = Binder.getCallingUid();
20577        if (callingUid != Process.SYSTEM_UID) {
20578            throw new SecurityException(
20579                    "addPersistentPreferredActivity can only be run by the system");
20580        }
20581        if (filter.countActions() == 0) {
20582            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20583            return;
20584        }
20585        synchronized (mPackages) {
20586            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20587                    ":");
20588            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20589            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20590                    new PersistentPreferredActivity(filter, activity));
20591            scheduleWritePackageRestrictionsLocked(userId);
20592            postPreferredActivityChangedBroadcast(userId);
20593        }
20594    }
20595
20596    @Override
20597    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20598        int callingUid = Binder.getCallingUid();
20599        if (callingUid != Process.SYSTEM_UID) {
20600            throw new SecurityException(
20601                    "clearPackagePersistentPreferredActivities can only be run by the system");
20602        }
20603        ArrayList<PersistentPreferredActivity> removed = null;
20604        boolean changed = false;
20605        synchronized (mPackages) {
20606            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20607                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20608                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20609                        .valueAt(i);
20610                if (userId != thisUserId) {
20611                    continue;
20612                }
20613                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20614                while (it.hasNext()) {
20615                    PersistentPreferredActivity ppa = it.next();
20616                    // Mark entry for removal only if it matches the package name.
20617                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20618                        if (removed == null) {
20619                            removed = new ArrayList<PersistentPreferredActivity>();
20620                        }
20621                        removed.add(ppa);
20622                    }
20623                }
20624                if (removed != null) {
20625                    for (int j=0; j<removed.size(); j++) {
20626                        PersistentPreferredActivity ppa = removed.get(j);
20627                        ppir.removeFilter(ppa);
20628                    }
20629                    changed = true;
20630                }
20631            }
20632
20633            if (changed) {
20634                scheduleWritePackageRestrictionsLocked(userId);
20635                postPreferredActivityChangedBroadcast(userId);
20636            }
20637        }
20638    }
20639
20640    /**
20641     * Common machinery for picking apart a restored XML blob and passing
20642     * it to a caller-supplied functor to be applied to the running system.
20643     */
20644    private void restoreFromXml(XmlPullParser parser, int userId,
20645            String expectedStartTag, BlobXmlRestorer functor)
20646            throws IOException, XmlPullParserException {
20647        int type;
20648        while ((type = parser.next()) != XmlPullParser.START_TAG
20649                && type != XmlPullParser.END_DOCUMENT) {
20650        }
20651        if (type != XmlPullParser.START_TAG) {
20652            // oops didn't find a start tag?!
20653            if (DEBUG_BACKUP) {
20654                Slog.e(TAG, "Didn't find start tag during restore");
20655            }
20656            return;
20657        }
20658Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20659        // this is supposed to be TAG_PREFERRED_BACKUP
20660        if (!expectedStartTag.equals(parser.getName())) {
20661            if (DEBUG_BACKUP) {
20662                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20663            }
20664            return;
20665        }
20666
20667        // skip interfering stuff, then we're aligned with the backing implementation
20668        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20669Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20670        functor.apply(parser, userId);
20671    }
20672
20673    private interface BlobXmlRestorer {
20674        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20675    }
20676
20677    /**
20678     * Non-Binder method, support for the backup/restore mechanism: write the
20679     * full set of preferred activities in its canonical XML format.  Returns the
20680     * XML output as a byte array, or null if there is none.
20681     */
20682    @Override
20683    public byte[] getPreferredActivityBackup(int userId) {
20684        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20685            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20686        }
20687
20688        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20689        try {
20690            final XmlSerializer serializer = new FastXmlSerializer();
20691            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20692            serializer.startDocument(null, true);
20693            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20694
20695            synchronized (mPackages) {
20696                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20697            }
20698
20699            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20700            serializer.endDocument();
20701            serializer.flush();
20702        } catch (Exception e) {
20703            if (DEBUG_BACKUP) {
20704                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20705            }
20706            return null;
20707        }
20708
20709        return dataStream.toByteArray();
20710    }
20711
20712    @Override
20713    public void restorePreferredActivities(byte[] backup, int userId) {
20714        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20715            throw new SecurityException("Only the system may call restorePreferredActivities()");
20716        }
20717
20718        try {
20719            final XmlPullParser parser = Xml.newPullParser();
20720            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20721            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20722                    new BlobXmlRestorer() {
20723                        @Override
20724                        public void apply(XmlPullParser parser, int userId)
20725                                throws XmlPullParserException, IOException {
20726                            synchronized (mPackages) {
20727                                mSettings.readPreferredActivitiesLPw(parser, userId);
20728                            }
20729                        }
20730                    } );
20731        } catch (Exception e) {
20732            if (DEBUG_BACKUP) {
20733                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20734            }
20735        }
20736    }
20737
20738    /**
20739     * Non-Binder method, support for the backup/restore mechanism: write the
20740     * default browser (etc) settings in its canonical XML format.  Returns the default
20741     * browser XML representation as a byte array, or null if there is none.
20742     */
20743    @Override
20744    public byte[] getDefaultAppsBackup(int userId) {
20745        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20746            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20747        }
20748
20749        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20750        try {
20751            final XmlSerializer serializer = new FastXmlSerializer();
20752            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20753            serializer.startDocument(null, true);
20754            serializer.startTag(null, TAG_DEFAULT_APPS);
20755
20756            synchronized (mPackages) {
20757                mSettings.writeDefaultAppsLPr(serializer, userId);
20758            }
20759
20760            serializer.endTag(null, TAG_DEFAULT_APPS);
20761            serializer.endDocument();
20762            serializer.flush();
20763        } catch (Exception e) {
20764            if (DEBUG_BACKUP) {
20765                Slog.e(TAG, "Unable to write default apps for backup", e);
20766            }
20767            return null;
20768        }
20769
20770        return dataStream.toByteArray();
20771    }
20772
20773    @Override
20774    public void restoreDefaultApps(byte[] backup, int userId) {
20775        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20776            throw new SecurityException("Only the system may call restoreDefaultApps()");
20777        }
20778
20779        try {
20780            final XmlPullParser parser = Xml.newPullParser();
20781            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20782            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20783                    new BlobXmlRestorer() {
20784                        @Override
20785                        public void apply(XmlPullParser parser, int userId)
20786                                throws XmlPullParserException, IOException {
20787                            synchronized (mPackages) {
20788                                mSettings.readDefaultAppsLPw(parser, userId);
20789                            }
20790                        }
20791                    } );
20792        } catch (Exception e) {
20793            if (DEBUG_BACKUP) {
20794                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20795            }
20796        }
20797    }
20798
20799    @Override
20800    public byte[] getIntentFilterVerificationBackup(int userId) {
20801        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20802            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20803        }
20804
20805        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20806        try {
20807            final XmlSerializer serializer = new FastXmlSerializer();
20808            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20809            serializer.startDocument(null, true);
20810            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20811
20812            synchronized (mPackages) {
20813                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20814            }
20815
20816            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20817            serializer.endDocument();
20818            serializer.flush();
20819        } catch (Exception e) {
20820            if (DEBUG_BACKUP) {
20821                Slog.e(TAG, "Unable to write default apps for backup", e);
20822            }
20823            return null;
20824        }
20825
20826        return dataStream.toByteArray();
20827    }
20828
20829    @Override
20830    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20831        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20832            throw new SecurityException("Only the system may call restorePreferredActivities()");
20833        }
20834
20835        try {
20836            final XmlPullParser parser = Xml.newPullParser();
20837            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20838            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20839                    new BlobXmlRestorer() {
20840                        @Override
20841                        public void apply(XmlPullParser parser, int userId)
20842                                throws XmlPullParserException, IOException {
20843                            synchronized (mPackages) {
20844                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20845                                mSettings.writeLPr();
20846                            }
20847                        }
20848                    } );
20849        } catch (Exception e) {
20850            if (DEBUG_BACKUP) {
20851                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20852            }
20853        }
20854    }
20855
20856    @Override
20857    public byte[] getPermissionGrantBackup(int userId) {
20858        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20859            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20860        }
20861
20862        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20863        try {
20864            final XmlSerializer serializer = new FastXmlSerializer();
20865            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20866            serializer.startDocument(null, true);
20867            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20868
20869            synchronized (mPackages) {
20870                serializeRuntimePermissionGrantsLPr(serializer, userId);
20871            }
20872
20873            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20874            serializer.endDocument();
20875            serializer.flush();
20876        } catch (Exception e) {
20877            if (DEBUG_BACKUP) {
20878                Slog.e(TAG, "Unable to write default apps for backup", e);
20879            }
20880            return null;
20881        }
20882
20883        return dataStream.toByteArray();
20884    }
20885
20886    @Override
20887    public void restorePermissionGrants(byte[] backup, int userId) {
20888        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20889            throw new SecurityException("Only the system may call restorePermissionGrants()");
20890        }
20891
20892        try {
20893            final XmlPullParser parser = Xml.newPullParser();
20894            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20895            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20896                    new BlobXmlRestorer() {
20897                        @Override
20898                        public void apply(XmlPullParser parser, int userId)
20899                                throws XmlPullParserException, IOException {
20900                            synchronized (mPackages) {
20901                                processRestoredPermissionGrantsLPr(parser, userId);
20902                            }
20903                        }
20904                    } );
20905        } catch (Exception e) {
20906            if (DEBUG_BACKUP) {
20907                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20908            }
20909        }
20910    }
20911
20912    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20913            throws IOException {
20914        serializer.startTag(null, TAG_ALL_GRANTS);
20915
20916        final int N = mSettings.mPackages.size();
20917        for (int i = 0; i < N; i++) {
20918            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20919            boolean pkgGrantsKnown = false;
20920
20921            PermissionsState packagePerms = ps.getPermissionsState();
20922
20923            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20924                final int grantFlags = state.getFlags();
20925                // only look at grants that are not system/policy fixed
20926                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20927                    final boolean isGranted = state.isGranted();
20928                    // And only back up the user-twiddled state bits
20929                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20930                        final String packageName = mSettings.mPackages.keyAt(i);
20931                        if (!pkgGrantsKnown) {
20932                            serializer.startTag(null, TAG_GRANT);
20933                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20934                            pkgGrantsKnown = true;
20935                        }
20936
20937                        final boolean userSet =
20938                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20939                        final boolean userFixed =
20940                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20941                        final boolean revoke =
20942                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20943
20944                        serializer.startTag(null, TAG_PERMISSION);
20945                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20946                        if (isGranted) {
20947                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20948                        }
20949                        if (userSet) {
20950                            serializer.attribute(null, ATTR_USER_SET, "true");
20951                        }
20952                        if (userFixed) {
20953                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20954                        }
20955                        if (revoke) {
20956                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20957                        }
20958                        serializer.endTag(null, TAG_PERMISSION);
20959                    }
20960                }
20961            }
20962
20963            if (pkgGrantsKnown) {
20964                serializer.endTag(null, TAG_GRANT);
20965            }
20966        }
20967
20968        serializer.endTag(null, TAG_ALL_GRANTS);
20969    }
20970
20971    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20972            throws XmlPullParserException, IOException {
20973        String pkgName = null;
20974        int outerDepth = parser.getDepth();
20975        int type;
20976        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20977                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20978            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20979                continue;
20980            }
20981
20982            final String tagName = parser.getName();
20983            if (tagName.equals(TAG_GRANT)) {
20984                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20985                if (DEBUG_BACKUP) {
20986                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20987                }
20988            } else if (tagName.equals(TAG_PERMISSION)) {
20989
20990                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20991                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20992
20993                int newFlagSet = 0;
20994                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20995                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20996                }
20997                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20998                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20999                }
21000                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21001                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21002                }
21003                if (DEBUG_BACKUP) {
21004                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21005                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21006                }
21007                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21008                if (ps != null) {
21009                    // Already installed so we apply the grant immediately
21010                    if (DEBUG_BACKUP) {
21011                        Slog.v(TAG, "        + already installed; applying");
21012                    }
21013                    PermissionsState perms = ps.getPermissionsState();
21014                    BasePermission bp = mSettings.mPermissions.get(permName);
21015                    if (bp != null) {
21016                        if (isGranted) {
21017                            perms.grantRuntimePermission(bp, userId);
21018                        }
21019                        if (newFlagSet != 0) {
21020                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21021                        }
21022                    }
21023                } else {
21024                    // Need to wait for post-restore install to apply the grant
21025                    if (DEBUG_BACKUP) {
21026                        Slog.v(TAG, "        - not yet installed; saving for later");
21027                    }
21028                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21029                            isGranted, newFlagSet, userId);
21030                }
21031            } else {
21032                PackageManagerService.reportSettingsProblem(Log.WARN,
21033                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21034                XmlUtils.skipCurrentTag(parser);
21035            }
21036        }
21037
21038        scheduleWriteSettingsLocked();
21039        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21040    }
21041
21042    @Override
21043    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21044            int sourceUserId, int targetUserId, int flags) {
21045        mContext.enforceCallingOrSelfPermission(
21046                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21047        int callingUid = Binder.getCallingUid();
21048        enforceOwnerRights(ownerPackage, callingUid);
21049        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21050        if (intentFilter.countActions() == 0) {
21051            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21052            return;
21053        }
21054        synchronized (mPackages) {
21055            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21056                    ownerPackage, targetUserId, flags);
21057            CrossProfileIntentResolver resolver =
21058                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21059            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21060            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21061            if (existing != null) {
21062                int size = existing.size();
21063                for (int i = 0; i < size; i++) {
21064                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21065                        return;
21066                    }
21067                }
21068            }
21069            resolver.addFilter(newFilter);
21070            scheduleWritePackageRestrictionsLocked(sourceUserId);
21071        }
21072    }
21073
21074    @Override
21075    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21076        mContext.enforceCallingOrSelfPermission(
21077                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21078        final int callingUid = Binder.getCallingUid();
21079        enforceOwnerRights(ownerPackage, callingUid);
21080        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21081        synchronized (mPackages) {
21082            CrossProfileIntentResolver resolver =
21083                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21084            ArraySet<CrossProfileIntentFilter> set =
21085                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21086            for (CrossProfileIntentFilter filter : set) {
21087                if (filter.getOwnerPackage().equals(ownerPackage)) {
21088                    resolver.removeFilter(filter);
21089                }
21090            }
21091            scheduleWritePackageRestrictionsLocked(sourceUserId);
21092        }
21093    }
21094
21095    // Enforcing that callingUid is owning pkg on userId
21096    private void enforceOwnerRights(String pkg, int callingUid) {
21097        // The system owns everything.
21098        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21099            return;
21100        }
21101        final int callingUserId = UserHandle.getUserId(callingUid);
21102        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21103        if (pi == null) {
21104            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21105                    + callingUserId);
21106        }
21107        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21108            throw new SecurityException("Calling uid " + callingUid
21109                    + " does not own package " + pkg);
21110        }
21111    }
21112
21113    @Override
21114    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21115        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21116            return null;
21117        }
21118        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21119    }
21120
21121    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21122        UserManagerService ums = UserManagerService.getInstance();
21123        if (ums != null) {
21124            final UserInfo parent = ums.getProfileParent(userId);
21125            final int launcherUid = (parent != null) ? parent.id : userId;
21126            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21127            if (launcherComponent != null) {
21128                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21129                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21130                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21131                        .setPackage(launcherComponent.getPackageName());
21132                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21133            }
21134        }
21135    }
21136
21137    /**
21138     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21139     * then reports the most likely home activity or null if there are more than one.
21140     */
21141    private ComponentName getDefaultHomeActivity(int userId) {
21142        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21143        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21144        if (cn != null) {
21145            return cn;
21146        }
21147
21148        // Find the launcher with the highest priority and return that component if there are no
21149        // other home activity with the same priority.
21150        int lastPriority = Integer.MIN_VALUE;
21151        ComponentName lastComponent = null;
21152        final int size = allHomeCandidates.size();
21153        for (int i = 0; i < size; i++) {
21154            final ResolveInfo ri = allHomeCandidates.get(i);
21155            if (ri.priority > lastPriority) {
21156                lastComponent = ri.activityInfo.getComponentName();
21157                lastPriority = ri.priority;
21158            } else if (ri.priority == lastPriority) {
21159                // Two components found with same priority.
21160                lastComponent = null;
21161            }
21162        }
21163        return lastComponent;
21164    }
21165
21166    private Intent getHomeIntent() {
21167        Intent intent = new Intent(Intent.ACTION_MAIN);
21168        intent.addCategory(Intent.CATEGORY_HOME);
21169        intent.addCategory(Intent.CATEGORY_DEFAULT);
21170        return intent;
21171    }
21172
21173    private IntentFilter getHomeFilter() {
21174        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21175        filter.addCategory(Intent.CATEGORY_HOME);
21176        filter.addCategory(Intent.CATEGORY_DEFAULT);
21177        return filter;
21178    }
21179
21180    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21181            int userId) {
21182        Intent intent  = getHomeIntent();
21183        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21184                PackageManager.GET_META_DATA, userId);
21185        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21186                true, false, false, userId);
21187
21188        allHomeCandidates.clear();
21189        if (list != null) {
21190            for (ResolveInfo ri : list) {
21191                allHomeCandidates.add(ri);
21192            }
21193        }
21194        return (preferred == null || preferred.activityInfo == null)
21195                ? null
21196                : new ComponentName(preferred.activityInfo.packageName,
21197                        preferred.activityInfo.name);
21198    }
21199
21200    @Override
21201    public void setHomeActivity(ComponentName comp, int userId) {
21202        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21203            return;
21204        }
21205        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21206        getHomeActivitiesAsUser(homeActivities, userId);
21207
21208        boolean found = false;
21209
21210        final int size = homeActivities.size();
21211        final ComponentName[] set = new ComponentName[size];
21212        for (int i = 0; i < size; i++) {
21213            final ResolveInfo candidate = homeActivities.get(i);
21214            final ActivityInfo info = candidate.activityInfo;
21215            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21216            set[i] = activityName;
21217            if (!found && activityName.equals(comp)) {
21218                found = true;
21219            }
21220        }
21221        if (!found) {
21222            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21223                    + userId);
21224        }
21225        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21226                set, comp, userId);
21227    }
21228
21229    private @Nullable String getSetupWizardPackageName() {
21230        final Intent intent = new Intent(Intent.ACTION_MAIN);
21231        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21232
21233        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21234                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21235                        | MATCH_DISABLED_COMPONENTS,
21236                UserHandle.myUserId());
21237        if (matches.size() == 1) {
21238            return matches.get(0).getComponentInfo().packageName;
21239        } else {
21240            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21241                    + ": matches=" + matches);
21242            return null;
21243        }
21244    }
21245
21246    private @Nullable String getStorageManagerPackageName() {
21247        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21248
21249        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21250                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21251                        | MATCH_DISABLED_COMPONENTS,
21252                UserHandle.myUserId());
21253        if (matches.size() == 1) {
21254            return matches.get(0).getComponentInfo().packageName;
21255        } else {
21256            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21257                    + matches.size() + ": matches=" + matches);
21258            return null;
21259        }
21260    }
21261
21262    @Override
21263    public void setApplicationEnabledSetting(String appPackageName,
21264            int newState, int flags, int userId, String callingPackage) {
21265        if (!sUserManager.exists(userId)) return;
21266        if (callingPackage == null) {
21267            callingPackage = Integer.toString(Binder.getCallingUid());
21268        }
21269        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21270    }
21271
21272    @Override
21273    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21274        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21275        synchronized (mPackages) {
21276            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21277            if (pkgSetting != null) {
21278                pkgSetting.setUpdateAvailable(updateAvailable);
21279            }
21280        }
21281    }
21282
21283    @Override
21284    public void setComponentEnabledSetting(ComponentName componentName,
21285            int newState, int flags, int userId) {
21286        if (!sUserManager.exists(userId)) return;
21287        setEnabledSetting(componentName.getPackageName(),
21288                componentName.getClassName(), newState, flags, userId, null);
21289    }
21290
21291    private void setEnabledSetting(final String packageName, String className, int newState,
21292            final int flags, int userId, String callingPackage) {
21293        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21294              || newState == COMPONENT_ENABLED_STATE_ENABLED
21295              || newState == COMPONENT_ENABLED_STATE_DISABLED
21296              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21297              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21298            throw new IllegalArgumentException("Invalid new component state: "
21299                    + newState);
21300        }
21301        PackageSetting pkgSetting;
21302        final int callingUid = Binder.getCallingUid();
21303        final int permission;
21304        if (callingUid == Process.SYSTEM_UID) {
21305            permission = PackageManager.PERMISSION_GRANTED;
21306        } else {
21307            permission = mContext.checkCallingOrSelfPermission(
21308                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21309        }
21310        enforceCrossUserPermission(callingUid, userId,
21311                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21312        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21313        boolean sendNow = false;
21314        boolean isApp = (className == null);
21315        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21316        String componentName = isApp ? packageName : className;
21317        int packageUid = -1;
21318        ArrayList<String> components;
21319
21320        // reader
21321        synchronized (mPackages) {
21322            pkgSetting = mSettings.mPackages.get(packageName);
21323            if (pkgSetting == null) {
21324                if (!isCallerInstantApp) {
21325                    if (className == null) {
21326                        throw new IllegalArgumentException("Unknown package: " + packageName);
21327                    }
21328                    throw new IllegalArgumentException(
21329                            "Unknown component: " + packageName + "/" + className);
21330                } else {
21331                    // throw SecurityException to prevent leaking package information
21332                    throw new SecurityException(
21333                            "Attempt to change component state; "
21334                            + "pid=" + Binder.getCallingPid()
21335                            + ", uid=" + callingUid
21336                            + (className == null
21337                                    ? ", package=" + packageName
21338                                    : ", component=" + packageName + "/" + className));
21339                }
21340            }
21341        }
21342
21343        // Limit who can change which apps
21344        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21345            // Don't allow apps that don't have permission to modify other apps
21346            if (!allowedByPermission
21347                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21348                throw new SecurityException(
21349                        "Attempt to change component state; "
21350                        + "pid=" + Binder.getCallingPid()
21351                        + ", uid=" + callingUid
21352                        + (className == null
21353                                ? ", package=" + packageName
21354                                : ", component=" + packageName + "/" + className));
21355            }
21356            // Don't allow changing protected packages.
21357            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21358                throw new SecurityException("Cannot disable a protected package: " + packageName);
21359            }
21360        }
21361
21362        synchronized (mPackages) {
21363            if (callingUid == Process.SHELL_UID
21364                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21365                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21366                // unless it is a test package.
21367                int oldState = pkgSetting.getEnabled(userId);
21368                if (className == null
21369                    &&
21370                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21371                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21372                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21373                    &&
21374                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21375                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21376                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21377                    // ok
21378                } else {
21379                    throw new SecurityException(
21380                            "Shell cannot change component state for " + packageName + "/"
21381                            + className + " to " + newState);
21382                }
21383            }
21384            if (className == null) {
21385                // We're dealing with an application/package level state change
21386                if (pkgSetting.getEnabled(userId) == newState) {
21387                    // Nothing to do
21388                    return;
21389                }
21390                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21391                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21392                    // Don't care about who enables an app.
21393                    callingPackage = null;
21394                }
21395                pkgSetting.setEnabled(newState, userId, callingPackage);
21396                // pkgSetting.pkg.mSetEnabled = newState;
21397            } else {
21398                // We're dealing with a component level state change
21399                // First, verify that this is a valid class name.
21400                PackageParser.Package pkg = pkgSetting.pkg;
21401                if (pkg == null || !pkg.hasComponentClassName(className)) {
21402                    if (pkg != null &&
21403                            pkg.applicationInfo.targetSdkVersion >=
21404                                    Build.VERSION_CODES.JELLY_BEAN) {
21405                        throw new IllegalArgumentException("Component class " + className
21406                                + " does not exist in " + packageName);
21407                    } else {
21408                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21409                                + className + " does not exist in " + packageName);
21410                    }
21411                }
21412                switch (newState) {
21413                case COMPONENT_ENABLED_STATE_ENABLED:
21414                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21415                        return;
21416                    }
21417                    break;
21418                case COMPONENT_ENABLED_STATE_DISABLED:
21419                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21420                        return;
21421                    }
21422                    break;
21423                case COMPONENT_ENABLED_STATE_DEFAULT:
21424                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21425                        return;
21426                    }
21427                    break;
21428                default:
21429                    Slog.e(TAG, "Invalid new component state: " + newState);
21430                    return;
21431                }
21432            }
21433            scheduleWritePackageRestrictionsLocked(userId);
21434            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21435            final long callingId = Binder.clearCallingIdentity();
21436            try {
21437                updateInstantAppInstallerLocked(packageName);
21438            } finally {
21439                Binder.restoreCallingIdentity(callingId);
21440            }
21441            components = mPendingBroadcasts.get(userId, packageName);
21442            final boolean newPackage = components == null;
21443            if (newPackage) {
21444                components = new ArrayList<String>();
21445            }
21446            if (!components.contains(componentName)) {
21447                components.add(componentName);
21448            }
21449            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21450                sendNow = true;
21451                // Purge entry from pending broadcast list if another one exists already
21452                // since we are sending one right away.
21453                mPendingBroadcasts.remove(userId, packageName);
21454            } else {
21455                if (newPackage) {
21456                    mPendingBroadcasts.put(userId, packageName, components);
21457                }
21458                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21459                    // Schedule a message
21460                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21461                }
21462            }
21463        }
21464
21465        long callingId = Binder.clearCallingIdentity();
21466        try {
21467            if (sendNow) {
21468                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21469                sendPackageChangedBroadcast(packageName,
21470                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21471            }
21472        } finally {
21473            Binder.restoreCallingIdentity(callingId);
21474        }
21475    }
21476
21477    @Override
21478    public void flushPackageRestrictionsAsUser(int userId) {
21479        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21480            return;
21481        }
21482        if (!sUserManager.exists(userId)) {
21483            return;
21484        }
21485        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21486                false /* checkShell */, "flushPackageRestrictions");
21487        synchronized (mPackages) {
21488            mSettings.writePackageRestrictionsLPr(userId);
21489            mDirtyUsers.remove(userId);
21490            if (mDirtyUsers.isEmpty()) {
21491                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21492            }
21493        }
21494    }
21495
21496    private void sendPackageChangedBroadcast(String packageName,
21497            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21498        if (DEBUG_INSTALL)
21499            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21500                    + componentNames);
21501        Bundle extras = new Bundle(4);
21502        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21503        String nameList[] = new String[componentNames.size()];
21504        componentNames.toArray(nameList);
21505        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21506        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21507        extras.putInt(Intent.EXTRA_UID, packageUid);
21508        // If this is not reporting a change of the overall package, then only send it
21509        // to registered receivers.  We don't want to launch a swath of apps for every
21510        // little component state change.
21511        final int flags = !componentNames.contains(packageName)
21512                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21513        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21514                new int[] {UserHandle.getUserId(packageUid)});
21515    }
21516
21517    @Override
21518    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21519        if (!sUserManager.exists(userId)) return;
21520        final int callingUid = Binder.getCallingUid();
21521        if (getInstantAppPackageName(callingUid) != null) {
21522            return;
21523        }
21524        final int permission = mContext.checkCallingOrSelfPermission(
21525                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21526        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21527        enforceCrossUserPermission(callingUid, userId,
21528                true /* requireFullPermission */, true /* checkShell */, "stop package");
21529        // writer
21530        synchronized (mPackages) {
21531            final PackageSetting ps = mSettings.mPackages.get(packageName);
21532            if (!filterAppAccessLPr(ps, callingUid, userId)
21533                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21534                            allowedByPermission, callingUid, userId)) {
21535                scheduleWritePackageRestrictionsLocked(userId);
21536            }
21537        }
21538    }
21539
21540    @Override
21541    public String getInstallerPackageName(String packageName) {
21542        final int callingUid = Binder.getCallingUid();
21543        if (getInstantAppPackageName(callingUid) != null) {
21544            return null;
21545        }
21546        // reader
21547        synchronized (mPackages) {
21548            final PackageSetting ps = mSettings.mPackages.get(packageName);
21549            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21550                return null;
21551            }
21552            return mSettings.getInstallerPackageNameLPr(packageName);
21553        }
21554    }
21555
21556    public boolean isOrphaned(String packageName) {
21557        // reader
21558        synchronized (mPackages) {
21559            return mSettings.isOrphaned(packageName);
21560        }
21561    }
21562
21563    @Override
21564    public int getApplicationEnabledSetting(String packageName, int userId) {
21565        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21566        int callingUid = Binder.getCallingUid();
21567        enforceCrossUserPermission(callingUid, userId,
21568                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21569        // reader
21570        synchronized (mPackages) {
21571            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21572                return COMPONENT_ENABLED_STATE_DISABLED;
21573            }
21574            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21575        }
21576    }
21577
21578    @Override
21579    public int getComponentEnabledSetting(ComponentName component, int userId) {
21580        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21581        int callingUid = Binder.getCallingUid();
21582        enforceCrossUserPermission(callingUid, userId,
21583                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21584        synchronized (mPackages) {
21585            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21586                    component, TYPE_UNKNOWN, userId)) {
21587                return COMPONENT_ENABLED_STATE_DISABLED;
21588            }
21589            return mSettings.getComponentEnabledSettingLPr(component, userId);
21590        }
21591    }
21592
21593    @Override
21594    public void enterSafeMode() {
21595        enforceSystemOrRoot("Only the system can request entering safe mode");
21596
21597        if (!mSystemReady) {
21598            mSafeMode = true;
21599        }
21600    }
21601
21602    @Override
21603    public void systemReady() {
21604        enforceSystemOrRoot("Only the system can claim the system is ready");
21605
21606        mSystemReady = true;
21607        final ContentResolver resolver = mContext.getContentResolver();
21608        ContentObserver co = new ContentObserver(mHandler) {
21609            @Override
21610            public void onChange(boolean selfChange) {
21611                mEphemeralAppsDisabled =
21612                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21613                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21614            }
21615        };
21616        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21617                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21618                false, co, UserHandle.USER_SYSTEM);
21619        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21620                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21621        co.onChange(true);
21622
21623        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21624        // disabled after already being started.
21625        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21626                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21627
21628        // Read the compatibilty setting when the system is ready.
21629        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21630                mContext.getContentResolver(),
21631                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21632        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21633        if (DEBUG_SETTINGS) {
21634            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21635        }
21636
21637        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21638
21639        synchronized (mPackages) {
21640            // Verify that all of the preferred activity components actually
21641            // exist.  It is possible for applications to be updated and at
21642            // that point remove a previously declared activity component that
21643            // had been set as a preferred activity.  We try to clean this up
21644            // the next time we encounter that preferred activity, but it is
21645            // possible for the user flow to never be able to return to that
21646            // situation so here we do a sanity check to make sure we haven't
21647            // left any junk around.
21648            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21649            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21650                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21651                removed.clear();
21652                for (PreferredActivity pa : pir.filterSet()) {
21653                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21654                        removed.add(pa);
21655                    }
21656                }
21657                if (removed.size() > 0) {
21658                    for (int r=0; r<removed.size(); r++) {
21659                        PreferredActivity pa = removed.get(r);
21660                        Slog.w(TAG, "Removing dangling preferred activity: "
21661                                + pa.mPref.mComponent);
21662                        pir.removeFilter(pa);
21663                    }
21664                    mSettings.writePackageRestrictionsLPr(
21665                            mSettings.mPreferredActivities.keyAt(i));
21666                }
21667            }
21668
21669            for (int userId : UserManagerService.getInstance().getUserIds()) {
21670                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21671                    grantPermissionsUserIds = ArrayUtils.appendInt(
21672                            grantPermissionsUserIds, userId);
21673                }
21674            }
21675        }
21676        sUserManager.systemReady();
21677
21678        // If we upgraded grant all default permissions before kicking off.
21679        for (int userId : grantPermissionsUserIds) {
21680            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21681        }
21682
21683        // If we did not grant default permissions, we preload from this the
21684        // default permission exceptions lazily to ensure we don't hit the
21685        // disk on a new user creation.
21686        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21687            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21688        }
21689
21690        // Kick off any messages waiting for system ready
21691        if (mPostSystemReadyMessages != null) {
21692            for (Message msg : mPostSystemReadyMessages) {
21693                msg.sendToTarget();
21694            }
21695            mPostSystemReadyMessages = null;
21696        }
21697
21698        // Watch for external volumes that come and go over time
21699        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21700        storage.registerListener(mStorageListener);
21701
21702        mInstallerService.systemReady();
21703        mPackageDexOptimizer.systemReady();
21704
21705        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21706                StorageManagerInternal.class);
21707        StorageManagerInternal.addExternalStoragePolicy(
21708                new StorageManagerInternal.ExternalStorageMountPolicy() {
21709            @Override
21710            public int getMountMode(int uid, String packageName) {
21711                if (Process.isIsolated(uid)) {
21712                    return Zygote.MOUNT_EXTERNAL_NONE;
21713                }
21714                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21715                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21716                }
21717                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21718                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21719                }
21720                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21721                    return Zygote.MOUNT_EXTERNAL_READ;
21722                }
21723                return Zygote.MOUNT_EXTERNAL_WRITE;
21724            }
21725
21726            @Override
21727            public boolean hasExternalStorage(int uid, String packageName) {
21728                return true;
21729            }
21730        });
21731
21732        // Now that we're mostly running, clean up stale users and apps
21733        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21734        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21735
21736        if (mPrivappPermissionsViolations != null) {
21737            Slog.wtf(TAG,"Signature|privileged permissions not in "
21738                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21739            mPrivappPermissionsViolations = null;
21740        }
21741    }
21742
21743    public void waitForAppDataPrepared() {
21744        if (mPrepareAppDataFuture == null) {
21745            return;
21746        }
21747        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21748        mPrepareAppDataFuture = null;
21749    }
21750
21751    @Override
21752    public boolean isSafeMode() {
21753        // allow instant applications
21754        return mSafeMode;
21755    }
21756
21757    @Override
21758    public boolean hasSystemUidErrors() {
21759        // allow instant applications
21760        return mHasSystemUidErrors;
21761    }
21762
21763    static String arrayToString(int[] array) {
21764        StringBuffer buf = new StringBuffer(128);
21765        buf.append('[');
21766        if (array != null) {
21767            for (int i=0; i<array.length; i++) {
21768                if (i > 0) buf.append(", ");
21769                buf.append(array[i]);
21770            }
21771        }
21772        buf.append(']');
21773        return buf.toString();
21774    }
21775
21776    static class DumpState {
21777        public static final int DUMP_LIBS = 1 << 0;
21778        public static final int DUMP_FEATURES = 1 << 1;
21779        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21780        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21781        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21782        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21783        public static final int DUMP_PERMISSIONS = 1 << 6;
21784        public static final int DUMP_PACKAGES = 1 << 7;
21785        public static final int DUMP_SHARED_USERS = 1 << 8;
21786        public static final int DUMP_MESSAGES = 1 << 9;
21787        public static final int DUMP_PROVIDERS = 1 << 10;
21788        public static final int DUMP_VERIFIERS = 1 << 11;
21789        public static final int DUMP_PREFERRED = 1 << 12;
21790        public static final int DUMP_PREFERRED_XML = 1 << 13;
21791        public static final int DUMP_KEYSETS = 1 << 14;
21792        public static final int DUMP_VERSION = 1 << 15;
21793        public static final int DUMP_INSTALLS = 1 << 16;
21794        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21795        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21796        public static final int DUMP_FROZEN = 1 << 19;
21797        public static final int DUMP_DEXOPT = 1 << 20;
21798        public static final int DUMP_COMPILER_STATS = 1 << 21;
21799        public static final int DUMP_CHANGES = 1 << 22;
21800
21801        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21802
21803        private int mTypes;
21804
21805        private int mOptions;
21806
21807        private boolean mTitlePrinted;
21808
21809        private SharedUserSetting mSharedUser;
21810
21811        public boolean isDumping(int type) {
21812            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21813                return true;
21814            }
21815
21816            return (mTypes & type) != 0;
21817        }
21818
21819        public void setDump(int type) {
21820            mTypes |= type;
21821        }
21822
21823        public boolean isOptionEnabled(int option) {
21824            return (mOptions & option) != 0;
21825        }
21826
21827        public void setOptionEnabled(int option) {
21828            mOptions |= option;
21829        }
21830
21831        public boolean onTitlePrinted() {
21832            final boolean printed = mTitlePrinted;
21833            mTitlePrinted = true;
21834            return printed;
21835        }
21836
21837        public boolean getTitlePrinted() {
21838            return mTitlePrinted;
21839        }
21840
21841        public void setTitlePrinted(boolean enabled) {
21842            mTitlePrinted = enabled;
21843        }
21844
21845        public SharedUserSetting getSharedUser() {
21846            return mSharedUser;
21847        }
21848
21849        public void setSharedUser(SharedUserSetting user) {
21850            mSharedUser = user;
21851        }
21852    }
21853
21854    @Override
21855    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21856            FileDescriptor err, String[] args, ShellCallback callback,
21857            ResultReceiver resultReceiver) {
21858        (new PackageManagerShellCommand(this)).exec(
21859                this, in, out, err, args, callback, resultReceiver);
21860    }
21861
21862    @Override
21863    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21864        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21865
21866        DumpState dumpState = new DumpState();
21867        boolean fullPreferred = false;
21868        boolean checkin = false;
21869
21870        String packageName = null;
21871        ArraySet<String> permissionNames = null;
21872
21873        int opti = 0;
21874        while (opti < args.length) {
21875            String opt = args[opti];
21876            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21877                break;
21878            }
21879            opti++;
21880
21881            if ("-a".equals(opt)) {
21882                // Right now we only know how to print all.
21883            } else if ("-h".equals(opt)) {
21884                pw.println("Package manager dump options:");
21885                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21886                pw.println("    --checkin: dump for a checkin");
21887                pw.println("    -f: print details of intent filters");
21888                pw.println("    -h: print this help");
21889                pw.println("  cmd may be one of:");
21890                pw.println("    l[ibraries]: list known shared libraries");
21891                pw.println("    f[eatures]: list device features");
21892                pw.println("    k[eysets]: print known keysets");
21893                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21894                pw.println("    perm[issions]: dump permissions");
21895                pw.println("    permission [name ...]: dump declaration and use of given permission");
21896                pw.println("    pref[erred]: print preferred package settings");
21897                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21898                pw.println("    prov[iders]: dump content providers");
21899                pw.println("    p[ackages]: dump installed packages");
21900                pw.println("    s[hared-users]: dump shared user IDs");
21901                pw.println("    m[essages]: print collected runtime messages");
21902                pw.println("    v[erifiers]: print package verifier info");
21903                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21904                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21905                pw.println("    version: print database version info");
21906                pw.println("    write: write current settings now");
21907                pw.println("    installs: details about install sessions");
21908                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21909                pw.println("    dexopt: dump dexopt state");
21910                pw.println("    compiler-stats: dump compiler statistics");
21911                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21912                pw.println("    <package.name>: info about given package");
21913                return;
21914            } else if ("--checkin".equals(opt)) {
21915                checkin = true;
21916            } else if ("-f".equals(opt)) {
21917                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21918            } else if ("--proto".equals(opt)) {
21919                dumpProto(fd);
21920                return;
21921            } else {
21922                pw.println("Unknown argument: " + opt + "; use -h for help");
21923            }
21924        }
21925
21926        // Is the caller requesting to dump a particular piece of data?
21927        if (opti < args.length) {
21928            String cmd = args[opti];
21929            opti++;
21930            // Is this a package name?
21931            if ("android".equals(cmd) || cmd.contains(".")) {
21932                packageName = cmd;
21933                // When dumping a single package, we always dump all of its
21934                // filter information since the amount of data will be reasonable.
21935                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21936            } else if ("check-permission".equals(cmd)) {
21937                if (opti >= args.length) {
21938                    pw.println("Error: check-permission missing permission argument");
21939                    return;
21940                }
21941                String perm = args[opti];
21942                opti++;
21943                if (opti >= args.length) {
21944                    pw.println("Error: check-permission missing package argument");
21945                    return;
21946                }
21947
21948                String pkg = args[opti];
21949                opti++;
21950                int user = UserHandle.getUserId(Binder.getCallingUid());
21951                if (opti < args.length) {
21952                    try {
21953                        user = Integer.parseInt(args[opti]);
21954                    } catch (NumberFormatException e) {
21955                        pw.println("Error: check-permission user argument is not a number: "
21956                                + args[opti]);
21957                        return;
21958                    }
21959                }
21960
21961                // Normalize package name to handle renamed packages and static libs
21962                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21963
21964                pw.println(checkPermission(perm, pkg, user));
21965                return;
21966            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21967                dumpState.setDump(DumpState.DUMP_LIBS);
21968            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21969                dumpState.setDump(DumpState.DUMP_FEATURES);
21970            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21971                if (opti >= args.length) {
21972                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21973                            | DumpState.DUMP_SERVICE_RESOLVERS
21974                            | DumpState.DUMP_RECEIVER_RESOLVERS
21975                            | DumpState.DUMP_CONTENT_RESOLVERS);
21976                } else {
21977                    while (opti < args.length) {
21978                        String name = args[opti];
21979                        if ("a".equals(name) || "activity".equals(name)) {
21980                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21981                        } else if ("s".equals(name) || "service".equals(name)) {
21982                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21983                        } else if ("r".equals(name) || "receiver".equals(name)) {
21984                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21985                        } else if ("c".equals(name) || "content".equals(name)) {
21986                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21987                        } else {
21988                            pw.println("Error: unknown resolver table type: " + name);
21989                            return;
21990                        }
21991                        opti++;
21992                    }
21993                }
21994            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21995                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21996            } else if ("permission".equals(cmd)) {
21997                if (opti >= args.length) {
21998                    pw.println("Error: permission requires permission name");
21999                    return;
22000                }
22001                permissionNames = new ArraySet<>();
22002                while (opti < args.length) {
22003                    permissionNames.add(args[opti]);
22004                    opti++;
22005                }
22006                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22007                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22008            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22009                dumpState.setDump(DumpState.DUMP_PREFERRED);
22010            } else if ("preferred-xml".equals(cmd)) {
22011                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22012                if (opti < args.length && "--full".equals(args[opti])) {
22013                    fullPreferred = true;
22014                    opti++;
22015                }
22016            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22017                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22018            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22019                dumpState.setDump(DumpState.DUMP_PACKAGES);
22020            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22021                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22022            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22023                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22024            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22025                dumpState.setDump(DumpState.DUMP_MESSAGES);
22026            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22027                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22028            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22029                    || "intent-filter-verifiers".equals(cmd)) {
22030                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22031            } else if ("version".equals(cmd)) {
22032                dumpState.setDump(DumpState.DUMP_VERSION);
22033            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22034                dumpState.setDump(DumpState.DUMP_KEYSETS);
22035            } else if ("installs".equals(cmd)) {
22036                dumpState.setDump(DumpState.DUMP_INSTALLS);
22037            } else if ("frozen".equals(cmd)) {
22038                dumpState.setDump(DumpState.DUMP_FROZEN);
22039            } else if ("dexopt".equals(cmd)) {
22040                dumpState.setDump(DumpState.DUMP_DEXOPT);
22041            } else if ("compiler-stats".equals(cmd)) {
22042                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22043            } else if ("changes".equals(cmd)) {
22044                dumpState.setDump(DumpState.DUMP_CHANGES);
22045            } else if ("write".equals(cmd)) {
22046                synchronized (mPackages) {
22047                    mSettings.writeLPr();
22048                    pw.println("Settings written.");
22049                    return;
22050                }
22051            }
22052        }
22053
22054        if (checkin) {
22055            pw.println("vers,1");
22056        }
22057
22058        // reader
22059        synchronized (mPackages) {
22060            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22061                if (!checkin) {
22062                    if (dumpState.onTitlePrinted())
22063                        pw.println();
22064                    pw.println("Database versions:");
22065                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22066                }
22067            }
22068
22069            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22070                if (!checkin) {
22071                    if (dumpState.onTitlePrinted())
22072                        pw.println();
22073                    pw.println("Verifiers:");
22074                    pw.print("  Required: ");
22075                    pw.print(mRequiredVerifierPackage);
22076                    pw.print(" (uid=");
22077                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22078                            UserHandle.USER_SYSTEM));
22079                    pw.println(")");
22080                } else if (mRequiredVerifierPackage != null) {
22081                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22082                    pw.print(",");
22083                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22084                            UserHandle.USER_SYSTEM));
22085                }
22086            }
22087
22088            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22089                    packageName == null) {
22090                if (mIntentFilterVerifierComponent != null) {
22091                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22092                    if (!checkin) {
22093                        if (dumpState.onTitlePrinted())
22094                            pw.println();
22095                        pw.println("Intent Filter Verifier:");
22096                        pw.print("  Using: ");
22097                        pw.print(verifierPackageName);
22098                        pw.print(" (uid=");
22099                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22100                                UserHandle.USER_SYSTEM));
22101                        pw.println(")");
22102                    } else if (verifierPackageName != null) {
22103                        pw.print("ifv,"); pw.print(verifierPackageName);
22104                        pw.print(",");
22105                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22106                                UserHandle.USER_SYSTEM));
22107                    }
22108                } else {
22109                    pw.println();
22110                    pw.println("No Intent Filter Verifier available!");
22111                }
22112            }
22113
22114            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22115                boolean printedHeader = false;
22116                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22117                while (it.hasNext()) {
22118                    String libName = it.next();
22119                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22120                    if (versionedLib == null) {
22121                        continue;
22122                    }
22123                    final int versionCount = versionedLib.size();
22124                    for (int i = 0; i < versionCount; i++) {
22125                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22126                        if (!checkin) {
22127                            if (!printedHeader) {
22128                                if (dumpState.onTitlePrinted())
22129                                    pw.println();
22130                                pw.println("Libraries:");
22131                                printedHeader = true;
22132                            }
22133                            pw.print("  ");
22134                        } else {
22135                            pw.print("lib,");
22136                        }
22137                        pw.print(libEntry.info.getName());
22138                        if (libEntry.info.isStatic()) {
22139                            pw.print(" version=" + libEntry.info.getVersion());
22140                        }
22141                        if (!checkin) {
22142                            pw.print(" -> ");
22143                        }
22144                        if (libEntry.path != null) {
22145                            pw.print(" (jar) ");
22146                            pw.print(libEntry.path);
22147                        } else {
22148                            pw.print(" (apk) ");
22149                            pw.print(libEntry.apk);
22150                        }
22151                        pw.println();
22152                    }
22153                }
22154            }
22155
22156            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22157                if (dumpState.onTitlePrinted())
22158                    pw.println();
22159                if (!checkin) {
22160                    pw.println("Features:");
22161                }
22162
22163                synchronized (mAvailableFeatures) {
22164                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22165                        if (checkin) {
22166                            pw.print("feat,");
22167                            pw.print(feat.name);
22168                            pw.print(",");
22169                            pw.println(feat.version);
22170                        } else {
22171                            pw.print("  ");
22172                            pw.print(feat.name);
22173                            if (feat.version > 0) {
22174                                pw.print(" version=");
22175                                pw.print(feat.version);
22176                            }
22177                            pw.println();
22178                        }
22179                    }
22180                }
22181            }
22182
22183            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22184                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22185                        : "Activity Resolver Table:", "  ", packageName,
22186                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22187                    dumpState.setTitlePrinted(true);
22188                }
22189            }
22190            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22191                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22192                        : "Receiver Resolver Table:", "  ", packageName,
22193                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22194                    dumpState.setTitlePrinted(true);
22195                }
22196            }
22197            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22198                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22199                        : "Service Resolver Table:", "  ", packageName,
22200                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22201                    dumpState.setTitlePrinted(true);
22202                }
22203            }
22204            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22205                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22206                        : "Provider Resolver Table:", "  ", packageName,
22207                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22208                    dumpState.setTitlePrinted(true);
22209                }
22210            }
22211
22212            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22213                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22214                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22215                    int user = mSettings.mPreferredActivities.keyAt(i);
22216                    if (pir.dump(pw,
22217                            dumpState.getTitlePrinted()
22218                                ? "\nPreferred Activities User " + user + ":"
22219                                : "Preferred Activities User " + user + ":", "  ",
22220                            packageName, true, false)) {
22221                        dumpState.setTitlePrinted(true);
22222                    }
22223                }
22224            }
22225
22226            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22227                pw.flush();
22228                FileOutputStream fout = new FileOutputStream(fd);
22229                BufferedOutputStream str = new BufferedOutputStream(fout);
22230                XmlSerializer serializer = new FastXmlSerializer();
22231                try {
22232                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22233                    serializer.startDocument(null, true);
22234                    serializer.setFeature(
22235                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22236                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22237                    serializer.endDocument();
22238                    serializer.flush();
22239                } catch (IllegalArgumentException e) {
22240                    pw.println("Failed writing: " + e);
22241                } catch (IllegalStateException e) {
22242                    pw.println("Failed writing: " + e);
22243                } catch (IOException e) {
22244                    pw.println("Failed writing: " + e);
22245                }
22246            }
22247
22248            if (!checkin
22249                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22250                    && packageName == null) {
22251                pw.println();
22252                int count = mSettings.mPackages.size();
22253                if (count == 0) {
22254                    pw.println("No applications!");
22255                    pw.println();
22256                } else {
22257                    final String prefix = "  ";
22258                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22259                    if (allPackageSettings.size() == 0) {
22260                        pw.println("No domain preferred apps!");
22261                        pw.println();
22262                    } else {
22263                        pw.println("App verification status:");
22264                        pw.println();
22265                        count = 0;
22266                        for (PackageSetting ps : allPackageSettings) {
22267                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22268                            if (ivi == null || ivi.getPackageName() == null) continue;
22269                            pw.println(prefix + "Package: " + ivi.getPackageName());
22270                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22271                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22272                            pw.println();
22273                            count++;
22274                        }
22275                        if (count == 0) {
22276                            pw.println(prefix + "No app verification established.");
22277                            pw.println();
22278                        }
22279                        for (int userId : sUserManager.getUserIds()) {
22280                            pw.println("App linkages for user " + userId + ":");
22281                            pw.println();
22282                            count = 0;
22283                            for (PackageSetting ps : allPackageSettings) {
22284                                final long status = ps.getDomainVerificationStatusForUser(userId);
22285                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22286                                        && !DEBUG_DOMAIN_VERIFICATION) {
22287                                    continue;
22288                                }
22289                                pw.println(prefix + "Package: " + ps.name);
22290                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22291                                String statusStr = IntentFilterVerificationInfo.
22292                                        getStatusStringFromValue(status);
22293                                pw.println(prefix + "Status:  " + statusStr);
22294                                pw.println();
22295                                count++;
22296                            }
22297                            if (count == 0) {
22298                                pw.println(prefix + "No configured app linkages.");
22299                                pw.println();
22300                            }
22301                        }
22302                    }
22303                }
22304            }
22305
22306            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22307                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22308                if (packageName == null && permissionNames == null) {
22309                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22310                        if (iperm == 0) {
22311                            if (dumpState.onTitlePrinted())
22312                                pw.println();
22313                            pw.println("AppOp Permissions:");
22314                        }
22315                        pw.print("  AppOp Permission ");
22316                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22317                        pw.println(":");
22318                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22319                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22320                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22321                        }
22322                    }
22323                }
22324            }
22325
22326            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22327                boolean printedSomething = false;
22328                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22329                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22330                        continue;
22331                    }
22332                    if (!printedSomething) {
22333                        if (dumpState.onTitlePrinted())
22334                            pw.println();
22335                        pw.println("Registered ContentProviders:");
22336                        printedSomething = true;
22337                    }
22338                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22339                    pw.print("    "); pw.println(p.toString());
22340                }
22341                printedSomething = false;
22342                for (Map.Entry<String, PackageParser.Provider> entry :
22343                        mProvidersByAuthority.entrySet()) {
22344                    PackageParser.Provider p = entry.getValue();
22345                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22346                        continue;
22347                    }
22348                    if (!printedSomething) {
22349                        if (dumpState.onTitlePrinted())
22350                            pw.println();
22351                        pw.println("ContentProvider Authorities:");
22352                        printedSomething = true;
22353                    }
22354                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22355                    pw.print("    "); pw.println(p.toString());
22356                    if (p.info != null && p.info.applicationInfo != null) {
22357                        final String appInfo = p.info.applicationInfo.toString();
22358                        pw.print("      applicationInfo="); pw.println(appInfo);
22359                    }
22360                }
22361            }
22362
22363            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22364                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22365            }
22366
22367            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22368                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22369            }
22370
22371            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22372                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22373            }
22374
22375            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22376                if (dumpState.onTitlePrinted()) pw.println();
22377                pw.println("Package Changes:");
22378                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22379                final int K = mChangedPackages.size();
22380                for (int i = 0; i < K; i++) {
22381                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22382                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22383                    final int N = changes.size();
22384                    if (N == 0) {
22385                        pw.print("    "); pw.println("No packages changed");
22386                    } else {
22387                        for (int j = 0; j < N; j++) {
22388                            final String pkgName = changes.valueAt(j);
22389                            final int sequenceNumber = changes.keyAt(j);
22390                            pw.print("    ");
22391                            pw.print("seq=");
22392                            pw.print(sequenceNumber);
22393                            pw.print(", package=");
22394                            pw.println(pkgName);
22395                        }
22396                    }
22397                }
22398            }
22399
22400            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22401                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22402            }
22403
22404            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22405                // XXX should handle packageName != null by dumping only install data that
22406                // the given package is involved with.
22407                if (dumpState.onTitlePrinted()) pw.println();
22408
22409                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22410                ipw.println();
22411                ipw.println("Frozen packages:");
22412                ipw.increaseIndent();
22413                if (mFrozenPackages.size() == 0) {
22414                    ipw.println("(none)");
22415                } else {
22416                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22417                        ipw.println(mFrozenPackages.valueAt(i));
22418                    }
22419                }
22420                ipw.decreaseIndent();
22421            }
22422
22423            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22424                if (dumpState.onTitlePrinted()) pw.println();
22425                dumpDexoptStateLPr(pw, packageName);
22426            }
22427
22428            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22429                if (dumpState.onTitlePrinted()) pw.println();
22430                dumpCompilerStatsLPr(pw, packageName);
22431            }
22432
22433            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22434                if (dumpState.onTitlePrinted()) pw.println();
22435                mSettings.dumpReadMessagesLPr(pw, dumpState);
22436
22437                pw.println();
22438                pw.println("Package warning messages:");
22439                BufferedReader in = null;
22440                String line = null;
22441                try {
22442                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22443                    while ((line = in.readLine()) != null) {
22444                        if (line.contains("ignored: updated version")) continue;
22445                        pw.println(line);
22446                    }
22447                } catch (IOException ignored) {
22448                } finally {
22449                    IoUtils.closeQuietly(in);
22450                }
22451            }
22452
22453            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22454                BufferedReader in = null;
22455                String line = null;
22456                try {
22457                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22458                    while ((line = in.readLine()) != null) {
22459                        if (line.contains("ignored: updated version")) continue;
22460                        pw.print("msg,");
22461                        pw.println(line);
22462                    }
22463                } catch (IOException ignored) {
22464                } finally {
22465                    IoUtils.closeQuietly(in);
22466                }
22467            }
22468        }
22469
22470        // PackageInstaller should be called outside of mPackages lock
22471        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22472            // XXX should handle packageName != null by dumping only install data that
22473            // the given package is involved with.
22474            if (dumpState.onTitlePrinted()) pw.println();
22475            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22476        }
22477    }
22478
22479    private void dumpProto(FileDescriptor fd) {
22480        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22481
22482        synchronized (mPackages) {
22483            final long requiredVerifierPackageToken =
22484                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22485            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22486            proto.write(
22487                    PackageServiceDumpProto.PackageShortProto.UID,
22488                    getPackageUid(
22489                            mRequiredVerifierPackage,
22490                            MATCH_DEBUG_TRIAGED_MISSING,
22491                            UserHandle.USER_SYSTEM));
22492            proto.end(requiredVerifierPackageToken);
22493
22494            if (mIntentFilterVerifierComponent != null) {
22495                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22496                final long verifierPackageToken =
22497                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22498                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22499                proto.write(
22500                        PackageServiceDumpProto.PackageShortProto.UID,
22501                        getPackageUid(
22502                                verifierPackageName,
22503                                MATCH_DEBUG_TRIAGED_MISSING,
22504                                UserHandle.USER_SYSTEM));
22505                proto.end(verifierPackageToken);
22506            }
22507
22508            dumpSharedLibrariesProto(proto);
22509            dumpFeaturesProto(proto);
22510            mSettings.dumpPackagesProto(proto);
22511            mSettings.dumpSharedUsersProto(proto);
22512            dumpMessagesProto(proto);
22513        }
22514        proto.flush();
22515    }
22516
22517    private void dumpMessagesProto(ProtoOutputStream proto) {
22518        BufferedReader in = null;
22519        String line = null;
22520        try {
22521            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22522            while ((line = in.readLine()) != null) {
22523                if (line.contains("ignored: updated version")) continue;
22524                proto.write(PackageServiceDumpProto.MESSAGES, line);
22525            }
22526        } catch (IOException ignored) {
22527        } finally {
22528            IoUtils.closeQuietly(in);
22529        }
22530    }
22531
22532    private void dumpFeaturesProto(ProtoOutputStream proto) {
22533        synchronized (mAvailableFeatures) {
22534            final int count = mAvailableFeatures.size();
22535            for (int i = 0; i < count; i++) {
22536                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22537                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22538                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22539                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22540                proto.end(featureToken);
22541            }
22542        }
22543    }
22544
22545    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22546        final int count = mSharedLibraries.size();
22547        for (int i = 0; i < count; i++) {
22548            final String libName = mSharedLibraries.keyAt(i);
22549            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22550            if (versionedLib == null) {
22551                continue;
22552            }
22553            final int versionCount = versionedLib.size();
22554            for (int j = 0; j < versionCount; j++) {
22555                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22556                final long sharedLibraryToken =
22557                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22558                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22559                final boolean isJar = (libEntry.path != null);
22560                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22561                if (isJar) {
22562                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22563                } else {
22564                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22565                }
22566                proto.end(sharedLibraryToken);
22567            }
22568        }
22569    }
22570
22571    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22572        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22573        ipw.println();
22574        ipw.println("Dexopt state:");
22575        ipw.increaseIndent();
22576        Collection<PackageParser.Package> packages = null;
22577        if (packageName != null) {
22578            PackageParser.Package targetPackage = mPackages.get(packageName);
22579            if (targetPackage != null) {
22580                packages = Collections.singletonList(targetPackage);
22581            } else {
22582                ipw.println("Unable to find package: " + packageName);
22583                return;
22584            }
22585        } else {
22586            packages = mPackages.values();
22587        }
22588
22589        for (PackageParser.Package pkg : packages) {
22590            ipw.println("[" + pkg.packageName + "]");
22591            ipw.increaseIndent();
22592            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22593                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22594            ipw.decreaseIndent();
22595        }
22596    }
22597
22598    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22599        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22600        ipw.println();
22601        ipw.println("Compiler stats:");
22602        ipw.increaseIndent();
22603        Collection<PackageParser.Package> packages = null;
22604        if (packageName != null) {
22605            PackageParser.Package targetPackage = mPackages.get(packageName);
22606            if (targetPackage != null) {
22607                packages = Collections.singletonList(targetPackage);
22608            } else {
22609                ipw.println("Unable to find package: " + packageName);
22610                return;
22611            }
22612        } else {
22613            packages = mPackages.values();
22614        }
22615
22616        for (PackageParser.Package pkg : packages) {
22617            ipw.println("[" + pkg.packageName + "]");
22618            ipw.increaseIndent();
22619
22620            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22621            if (stats == null) {
22622                ipw.println("(No recorded stats)");
22623            } else {
22624                stats.dump(ipw);
22625            }
22626            ipw.decreaseIndent();
22627        }
22628    }
22629
22630    private String dumpDomainString(String packageName) {
22631        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22632                .getList();
22633        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22634
22635        ArraySet<String> result = new ArraySet<>();
22636        if (iviList.size() > 0) {
22637            for (IntentFilterVerificationInfo ivi : iviList) {
22638                for (String host : ivi.getDomains()) {
22639                    result.add(host);
22640                }
22641            }
22642        }
22643        if (filters != null && filters.size() > 0) {
22644            for (IntentFilter filter : filters) {
22645                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22646                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22647                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22648                    result.addAll(filter.getHostsList());
22649                }
22650            }
22651        }
22652
22653        StringBuilder sb = new StringBuilder(result.size() * 16);
22654        for (String domain : result) {
22655            if (sb.length() > 0) sb.append(" ");
22656            sb.append(domain);
22657        }
22658        return sb.toString();
22659    }
22660
22661    // ------- apps on sdcard specific code -------
22662    static final boolean DEBUG_SD_INSTALL = false;
22663
22664    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22665
22666    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22667
22668    private boolean mMediaMounted = false;
22669
22670    static String getEncryptKey() {
22671        try {
22672            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22673                    SD_ENCRYPTION_KEYSTORE_NAME);
22674            if (sdEncKey == null) {
22675                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22676                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22677                if (sdEncKey == null) {
22678                    Slog.e(TAG, "Failed to create encryption keys");
22679                    return null;
22680                }
22681            }
22682            return sdEncKey;
22683        } catch (NoSuchAlgorithmException nsae) {
22684            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22685            return null;
22686        } catch (IOException ioe) {
22687            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22688            return null;
22689        }
22690    }
22691
22692    /*
22693     * Update media status on PackageManager.
22694     */
22695    @Override
22696    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22697        enforceSystemOrRoot("Media status can only be updated by the system");
22698        // reader; this apparently protects mMediaMounted, but should probably
22699        // be a different lock in that case.
22700        synchronized (mPackages) {
22701            Log.i(TAG, "Updating external media status from "
22702                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22703                    + (mediaStatus ? "mounted" : "unmounted"));
22704            if (DEBUG_SD_INSTALL)
22705                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22706                        + ", mMediaMounted=" + mMediaMounted);
22707            if (mediaStatus == mMediaMounted) {
22708                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22709                        : 0, -1);
22710                mHandler.sendMessage(msg);
22711                return;
22712            }
22713            mMediaMounted = mediaStatus;
22714        }
22715        // Queue up an async operation since the package installation may take a
22716        // little while.
22717        mHandler.post(new Runnable() {
22718            public void run() {
22719                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22720            }
22721        });
22722    }
22723
22724    /**
22725     * Called by StorageManagerService when the initial ASECs to scan are available.
22726     * Should block until all the ASEC containers are finished being scanned.
22727     */
22728    public void scanAvailableAsecs() {
22729        updateExternalMediaStatusInner(true, false, false);
22730    }
22731
22732    /*
22733     * Collect information of applications on external media, map them against
22734     * existing containers and update information based on current mount status.
22735     * Please note that we always have to report status if reportStatus has been
22736     * set to true especially when unloading packages.
22737     */
22738    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22739            boolean externalStorage) {
22740        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22741        int[] uidArr = EmptyArray.INT;
22742
22743        final String[] list = PackageHelper.getSecureContainerList();
22744        if (ArrayUtils.isEmpty(list)) {
22745            Log.i(TAG, "No secure containers found");
22746        } else {
22747            // Process list of secure containers and categorize them
22748            // as active or stale based on their package internal state.
22749
22750            // reader
22751            synchronized (mPackages) {
22752                for (String cid : list) {
22753                    // Leave stages untouched for now; installer service owns them
22754                    if (PackageInstallerService.isStageName(cid)) continue;
22755
22756                    if (DEBUG_SD_INSTALL)
22757                        Log.i(TAG, "Processing container " + cid);
22758                    String pkgName = getAsecPackageName(cid);
22759                    if (pkgName == null) {
22760                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22761                        continue;
22762                    }
22763                    if (DEBUG_SD_INSTALL)
22764                        Log.i(TAG, "Looking for pkg : " + pkgName);
22765
22766                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22767                    if (ps == null) {
22768                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22769                        continue;
22770                    }
22771
22772                    /*
22773                     * Skip packages that are not external if we're unmounting
22774                     * external storage.
22775                     */
22776                    if (externalStorage && !isMounted && !isExternal(ps)) {
22777                        continue;
22778                    }
22779
22780                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22781                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22782                    // The package status is changed only if the code path
22783                    // matches between settings and the container id.
22784                    if (ps.codePathString != null
22785                            && ps.codePathString.startsWith(args.getCodePath())) {
22786                        if (DEBUG_SD_INSTALL) {
22787                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22788                                    + " at code path: " + ps.codePathString);
22789                        }
22790
22791                        // We do have a valid package installed on sdcard
22792                        processCids.put(args, ps.codePathString);
22793                        final int uid = ps.appId;
22794                        if (uid != -1) {
22795                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22796                        }
22797                    } else {
22798                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22799                                + ps.codePathString);
22800                    }
22801                }
22802            }
22803
22804            Arrays.sort(uidArr);
22805        }
22806
22807        // Process packages with valid entries.
22808        if (isMounted) {
22809            if (DEBUG_SD_INSTALL)
22810                Log.i(TAG, "Loading packages");
22811            loadMediaPackages(processCids, uidArr, externalStorage);
22812            startCleaningPackages();
22813            mInstallerService.onSecureContainersAvailable();
22814        } else {
22815            if (DEBUG_SD_INSTALL)
22816                Log.i(TAG, "Unloading packages");
22817            unloadMediaPackages(processCids, uidArr, reportStatus);
22818        }
22819    }
22820
22821    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22822            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22823        final int size = infos.size();
22824        final String[] packageNames = new String[size];
22825        final int[] packageUids = new int[size];
22826        for (int i = 0; i < size; i++) {
22827            final ApplicationInfo info = infos.get(i);
22828            packageNames[i] = info.packageName;
22829            packageUids[i] = info.uid;
22830        }
22831        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22832                finishedReceiver);
22833    }
22834
22835    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22836            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22837        sendResourcesChangedBroadcast(mediaStatus, replacing,
22838                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22839    }
22840
22841    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22842            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22843        int size = pkgList.length;
22844        if (size > 0) {
22845            // Send broadcasts here
22846            Bundle extras = new Bundle();
22847            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22848            if (uidArr != null) {
22849                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22850            }
22851            if (replacing) {
22852                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22853            }
22854            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22855                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22856            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22857        }
22858    }
22859
22860   /*
22861     * Look at potentially valid container ids from processCids If package
22862     * information doesn't match the one on record or package scanning fails,
22863     * the cid is added to list of removeCids. We currently don't delete stale
22864     * containers.
22865     */
22866    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22867            boolean externalStorage) {
22868        ArrayList<String> pkgList = new ArrayList<String>();
22869        Set<AsecInstallArgs> keys = processCids.keySet();
22870
22871        for (AsecInstallArgs args : keys) {
22872            String codePath = processCids.get(args);
22873            if (DEBUG_SD_INSTALL)
22874                Log.i(TAG, "Loading container : " + args.cid);
22875            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22876            try {
22877                // Make sure there are no container errors first.
22878                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22879                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22880                            + " when installing from sdcard");
22881                    continue;
22882                }
22883                // Check code path here.
22884                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22885                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22886                            + " does not match one in settings " + codePath);
22887                    continue;
22888                }
22889                // Parse package
22890                int parseFlags = mDefParseFlags;
22891                if (args.isExternalAsec()) {
22892                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22893                }
22894                if (args.isFwdLocked()) {
22895                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22896                }
22897
22898                synchronized (mInstallLock) {
22899                    PackageParser.Package pkg = null;
22900                    try {
22901                        // Sadly we don't know the package name yet to freeze it
22902                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22903                                SCAN_IGNORE_FROZEN, 0, null);
22904                    } catch (PackageManagerException e) {
22905                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22906                    }
22907                    // Scan the package
22908                    if (pkg != null) {
22909                        /*
22910                         * TODO why is the lock being held? doPostInstall is
22911                         * called in other places without the lock. This needs
22912                         * to be straightened out.
22913                         */
22914                        // writer
22915                        synchronized (mPackages) {
22916                            retCode = PackageManager.INSTALL_SUCCEEDED;
22917                            pkgList.add(pkg.packageName);
22918                            // Post process args
22919                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22920                                    pkg.applicationInfo.uid);
22921                        }
22922                    } else {
22923                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22924                    }
22925                }
22926
22927            } finally {
22928                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22929                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22930                }
22931            }
22932        }
22933        // writer
22934        synchronized (mPackages) {
22935            // If the platform SDK has changed since the last time we booted,
22936            // we need to re-grant app permission to catch any new ones that
22937            // appear. This is really a hack, and means that apps can in some
22938            // cases get permissions that the user didn't initially explicitly
22939            // allow... it would be nice to have some better way to handle
22940            // this situation.
22941            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22942                    : mSettings.getInternalVersion();
22943            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22944                    : StorageManager.UUID_PRIVATE_INTERNAL;
22945
22946            int updateFlags = UPDATE_PERMISSIONS_ALL;
22947            if (ver.sdkVersion != mSdkVersion) {
22948                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22949                        + mSdkVersion + "; regranting permissions for external");
22950                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22951            }
22952            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22953
22954            // Yay, everything is now upgraded
22955            ver.forceCurrent();
22956
22957            // can downgrade to reader
22958            // Persist settings
22959            mSettings.writeLPr();
22960        }
22961        // Send a broadcast to let everyone know we are done processing
22962        if (pkgList.size() > 0) {
22963            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22964        }
22965    }
22966
22967   /*
22968     * Utility method to unload a list of specified containers
22969     */
22970    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22971        // Just unmount all valid containers.
22972        for (AsecInstallArgs arg : cidArgs) {
22973            synchronized (mInstallLock) {
22974                arg.doPostDeleteLI(false);
22975           }
22976       }
22977   }
22978
22979    /*
22980     * Unload packages mounted on external media. This involves deleting package
22981     * data from internal structures, sending broadcasts about disabled packages,
22982     * gc'ing to free up references, unmounting all secure containers
22983     * corresponding to packages on external media, and posting a
22984     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22985     * that we always have to post this message if status has been requested no
22986     * matter what.
22987     */
22988    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22989            final boolean reportStatus) {
22990        if (DEBUG_SD_INSTALL)
22991            Log.i(TAG, "unloading media packages");
22992        ArrayList<String> pkgList = new ArrayList<String>();
22993        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22994        final Set<AsecInstallArgs> keys = processCids.keySet();
22995        for (AsecInstallArgs args : keys) {
22996            String pkgName = args.getPackageName();
22997            if (DEBUG_SD_INSTALL)
22998                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22999            // Delete package internally
23000            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23001            synchronized (mInstallLock) {
23002                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23003                final boolean res;
23004                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23005                        "unloadMediaPackages")) {
23006                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23007                            null);
23008                }
23009                if (res) {
23010                    pkgList.add(pkgName);
23011                } else {
23012                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23013                    failedList.add(args);
23014                }
23015            }
23016        }
23017
23018        // reader
23019        synchronized (mPackages) {
23020            // We didn't update the settings after removing each package;
23021            // write them now for all packages.
23022            mSettings.writeLPr();
23023        }
23024
23025        // We have to absolutely send UPDATED_MEDIA_STATUS only
23026        // after confirming that all the receivers processed the ordered
23027        // broadcast when packages get disabled, force a gc to clean things up.
23028        // and unload all the containers.
23029        if (pkgList.size() > 0) {
23030            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23031                    new IIntentReceiver.Stub() {
23032                public void performReceive(Intent intent, int resultCode, String data,
23033                        Bundle extras, boolean ordered, boolean sticky,
23034                        int sendingUser) throws RemoteException {
23035                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23036                            reportStatus ? 1 : 0, 1, keys);
23037                    mHandler.sendMessage(msg);
23038                }
23039            });
23040        } else {
23041            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23042                    keys);
23043            mHandler.sendMessage(msg);
23044        }
23045    }
23046
23047    private void loadPrivatePackages(final VolumeInfo vol) {
23048        mHandler.post(new Runnable() {
23049            @Override
23050            public void run() {
23051                loadPrivatePackagesInner(vol);
23052            }
23053        });
23054    }
23055
23056    private void loadPrivatePackagesInner(VolumeInfo vol) {
23057        final String volumeUuid = vol.fsUuid;
23058        if (TextUtils.isEmpty(volumeUuid)) {
23059            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23060            return;
23061        }
23062
23063        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23064        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23065        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23066
23067        final VersionInfo ver;
23068        final List<PackageSetting> packages;
23069        synchronized (mPackages) {
23070            ver = mSettings.findOrCreateVersion(volumeUuid);
23071            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23072        }
23073
23074        for (PackageSetting ps : packages) {
23075            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23076            synchronized (mInstallLock) {
23077                final PackageParser.Package pkg;
23078                try {
23079                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23080                    loaded.add(pkg.applicationInfo);
23081
23082                } catch (PackageManagerException e) {
23083                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23084                }
23085
23086                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23087                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23088                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23089                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23090                }
23091            }
23092        }
23093
23094        // Reconcile app data for all started/unlocked users
23095        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23096        final UserManager um = mContext.getSystemService(UserManager.class);
23097        UserManagerInternal umInternal = getUserManagerInternal();
23098        for (UserInfo user : um.getUsers()) {
23099            final int flags;
23100            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23101                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23102            } else if (umInternal.isUserRunning(user.id)) {
23103                flags = StorageManager.FLAG_STORAGE_DE;
23104            } else {
23105                continue;
23106            }
23107
23108            try {
23109                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23110                synchronized (mInstallLock) {
23111                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23112                }
23113            } catch (IllegalStateException e) {
23114                // Device was probably ejected, and we'll process that event momentarily
23115                Slog.w(TAG, "Failed to prepare storage: " + e);
23116            }
23117        }
23118
23119        synchronized (mPackages) {
23120            int updateFlags = UPDATE_PERMISSIONS_ALL;
23121            if (ver.sdkVersion != mSdkVersion) {
23122                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23123                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23124                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23125            }
23126            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23127
23128            // Yay, everything is now upgraded
23129            ver.forceCurrent();
23130
23131            mSettings.writeLPr();
23132        }
23133
23134        for (PackageFreezer freezer : freezers) {
23135            freezer.close();
23136        }
23137
23138        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23139        sendResourcesChangedBroadcast(true, false, loaded, null);
23140    }
23141
23142    private void unloadPrivatePackages(final VolumeInfo vol) {
23143        mHandler.post(new Runnable() {
23144            @Override
23145            public void run() {
23146                unloadPrivatePackagesInner(vol);
23147            }
23148        });
23149    }
23150
23151    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23152        final String volumeUuid = vol.fsUuid;
23153        if (TextUtils.isEmpty(volumeUuid)) {
23154            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23155            return;
23156        }
23157
23158        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23159        synchronized (mInstallLock) {
23160        synchronized (mPackages) {
23161            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23162            for (PackageSetting ps : packages) {
23163                if (ps.pkg == null) continue;
23164
23165                final ApplicationInfo info = ps.pkg.applicationInfo;
23166                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23167                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23168
23169                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23170                        "unloadPrivatePackagesInner")) {
23171                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23172                            false, null)) {
23173                        unloaded.add(info);
23174                    } else {
23175                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23176                    }
23177                }
23178
23179                // Try very hard to release any references to this package
23180                // so we don't risk the system server being killed due to
23181                // open FDs
23182                AttributeCache.instance().removePackage(ps.name);
23183            }
23184
23185            mSettings.writeLPr();
23186        }
23187        }
23188
23189        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23190        sendResourcesChangedBroadcast(false, false, unloaded, null);
23191
23192        // Try very hard to release any references to this path so we don't risk
23193        // the system server being killed due to open FDs
23194        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23195
23196        for (int i = 0; i < 3; i++) {
23197            System.gc();
23198            System.runFinalization();
23199        }
23200    }
23201
23202    private void assertPackageKnown(String volumeUuid, String packageName)
23203            throws PackageManagerException {
23204        synchronized (mPackages) {
23205            // Normalize package name to handle renamed packages
23206            packageName = normalizePackageNameLPr(packageName);
23207
23208            final PackageSetting ps = mSettings.mPackages.get(packageName);
23209            if (ps == null) {
23210                throw new PackageManagerException("Package " + packageName + " is unknown");
23211            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23212                throw new PackageManagerException(
23213                        "Package " + packageName + " found on unknown volume " + volumeUuid
23214                                + "; expected volume " + ps.volumeUuid);
23215            }
23216        }
23217    }
23218
23219    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23220            throws PackageManagerException {
23221        synchronized (mPackages) {
23222            // Normalize package name to handle renamed packages
23223            packageName = normalizePackageNameLPr(packageName);
23224
23225            final PackageSetting ps = mSettings.mPackages.get(packageName);
23226            if (ps == null) {
23227                throw new PackageManagerException("Package " + packageName + " is unknown");
23228            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23229                throw new PackageManagerException(
23230                        "Package " + packageName + " found on unknown volume " + volumeUuid
23231                                + "; expected volume " + ps.volumeUuid);
23232            } else if (!ps.getInstalled(userId)) {
23233                throw new PackageManagerException(
23234                        "Package " + packageName + " not installed for user " + userId);
23235            }
23236        }
23237    }
23238
23239    private List<String> collectAbsoluteCodePaths() {
23240        synchronized (mPackages) {
23241            List<String> codePaths = new ArrayList<>();
23242            final int packageCount = mSettings.mPackages.size();
23243            for (int i = 0; i < packageCount; i++) {
23244                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23245                codePaths.add(ps.codePath.getAbsolutePath());
23246            }
23247            return codePaths;
23248        }
23249    }
23250
23251    /**
23252     * Examine all apps present on given mounted volume, and destroy apps that
23253     * aren't expected, either due to uninstallation or reinstallation on
23254     * another volume.
23255     */
23256    private void reconcileApps(String volumeUuid) {
23257        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23258        List<File> filesToDelete = null;
23259
23260        final File[] files = FileUtils.listFilesOrEmpty(
23261                Environment.getDataAppDirectory(volumeUuid));
23262        for (File file : files) {
23263            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23264                    && !PackageInstallerService.isStageName(file.getName());
23265            if (!isPackage) {
23266                // Ignore entries which are not packages
23267                continue;
23268            }
23269
23270            String absolutePath = file.getAbsolutePath();
23271
23272            boolean pathValid = false;
23273            final int absoluteCodePathCount = absoluteCodePaths.size();
23274            for (int i = 0; i < absoluteCodePathCount; i++) {
23275                String absoluteCodePath = absoluteCodePaths.get(i);
23276                if (absolutePath.startsWith(absoluteCodePath)) {
23277                    pathValid = true;
23278                    break;
23279                }
23280            }
23281
23282            if (!pathValid) {
23283                if (filesToDelete == null) {
23284                    filesToDelete = new ArrayList<>();
23285                }
23286                filesToDelete.add(file);
23287            }
23288        }
23289
23290        if (filesToDelete != null) {
23291            final int fileToDeleteCount = filesToDelete.size();
23292            for (int i = 0; i < fileToDeleteCount; i++) {
23293                File fileToDelete = filesToDelete.get(i);
23294                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23295                synchronized (mInstallLock) {
23296                    removeCodePathLI(fileToDelete);
23297                }
23298            }
23299        }
23300    }
23301
23302    /**
23303     * Reconcile all app data for the given user.
23304     * <p>
23305     * Verifies that directories exist and that ownership and labeling is
23306     * correct for all installed apps on all mounted volumes.
23307     */
23308    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23309        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23310        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23311            final String volumeUuid = vol.getFsUuid();
23312            synchronized (mInstallLock) {
23313                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23314            }
23315        }
23316    }
23317
23318    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23319            boolean migrateAppData) {
23320        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23321    }
23322
23323    /**
23324     * Reconcile all app data on given mounted volume.
23325     * <p>
23326     * Destroys app data that isn't expected, either due to uninstallation or
23327     * reinstallation on another volume.
23328     * <p>
23329     * Verifies that directories exist and that ownership and labeling is
23330     * correct for all installed apps.
23331     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23332     */
23333    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23334            boolean migrateAppData, boolean onlyCoreApps) {
23335        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23336                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23337        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23338
23339        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23340        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23341
23342        // First look for stale data that doesn't belong, and check if things
23343        // have changed since we did our last restorecon
23344        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23345            if (StorageManager.isFileEncryptedNativeOrEmulated()
23346                    && !StorageManager.isUserKeyUnlocked(userId)) {
23347                throw new RuntimeException(
23348                        "Yikes, someone asked us to reconcile CE storage while " + userId
23349                                + " was still locked; this would have caused massive data loss!");
23350            }
23351
23352            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23353            for (File file : files) {
23354                final String packageName = file.getName();
23355                try {
23356                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23357                } catch (PackageManagerException e) {
23358                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23359                    try {
23360                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23361                                StorageManager.FLAG_STORAGE_CE, 0);
23362                    } catch (InstallerException e2) {
23363                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23364                    }
23365                }
23366            }
23367        }
23368        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23369            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23370            for (File file : files) {
23371                final String packageName = file.getName();
23372                try {
23373                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23374                } catch (PackageManagerException e) {
23375                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23376                    try {
23377                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23378                                StorageManager.FLAG_STORAGE_DE, 0);
23379                    } catch (InstallerException e2) {
23380                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23381                    }
23382                }
23383            }
23384        }
23385
23386        // Ensure that data directories are ready to roll for all packages
23387        // installed for this volume and user
23388        final List<PackageSetting> packages;
23389        synchronized (mPackages) {
23390            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23391        }
23392        int preparedCount = 0;
23393        for (PackageSetting ps : packages) {
23394            final String packageName = ps.name;
23395            if (ps.pkg == null) {
23396                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23397                // TODO: might be due to legacy ASEC apps; we should circle back
23398                // and reconcile again once they're scanned
23399                continue;
23400            }
23401            // Skip non-core apps if requested
23402            if (onlyCoreApps && !ps.pkg.coreApp) {
23403                result.add(packageName);
23404                continue;
23405            }
23406
23407            if (ps.getInstalled(userId)) {
23408                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23409                preparedCount++;
23410            }
23411        }
23412
23413        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23414        return result;
23415    }
23416
23417    /**
23418     * Prepare app data for the given app just after it was installed or
23419     * upgraded. This method carefully only touches users that it's installed
23420     * for, and it forces a restorecon to handle any seinfo changes.
23421     * <p>
23422     * Verifies that directories exist and that ownership and labeling is
23423     * correct for all installed apps. If there is an ownership mismatch, it
23424     * will try recovering system apps by wiping data; third-party app data is
23425     * left intact.
23426     * <p>
23427     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23428     */
23429    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23430        final PackageSetting ps;
23431        synchronized (mPackages) {
23432            ps = mSettings.mPackages.get(pkg.packageName);
23433            mSettings.writeKernelMappingLPr(ps);
23434        }
23435
23436        final UserManager um = mContext.getSystemService(UserManager.class);
23437        UserManagerInternal umInternal = getUserManagerInternal();
23438        for (UserInfo user : um.getUsers()) {
23439            final int flags;
23440            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23441                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23442            } else if (umInternal.isUserRunning(user.id)) {
23443                flags = StorageManager.FLAG_STORAGE_DE;
23444            } else {
23445                continue;
23446            }
23447
23448            if (ps.getInstalled(user.id)) {
23449                // TODO: when user data is locked, mark that we're still dirty
23450                prepareAppDataLIF(pkg, user.id, flags);
23451            }
23452        }
23453    }
23454
23455    /**
23456     * Prepare app data for the given app.
23457     * <p>
23458     * Verifies that directories exist and that ownership and labeling is
23459     * correct for all installed apps. If there is an ownership mismatch, this
23460     * will try recovering system apps by wiping data; third-party app data is
23461     * left intact.
23462     */
23463    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23464        if (pkg == null) {
23465            Slog.wtf(TAG, "Package was null!", new Throwable());
23466            return;
23467        }
23468        prepareAppDataLeafLIF(pkg, userId, flags);
23469        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23470        for (int i = 0; i < childCount; i++) {
23471            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23472        }
23473    }
23474
23475    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23476            boolean maybeMigrateAppData) {
23477        prepareAppDataLIF(pkg, userId, flags);
23478
23479        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23480            // We may have just shuffled around app data directories, so
23481            // prepare them one more time
23482            prepareAppDataLIF(pkg, userId, flags);
23483        }
23484    }
23485
23486    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23487        if (DEBUG_APP_DATA) {
23488            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23489                    + Integer.toHexString(flags));
23490        }
23491
23492        final String volumeUuid = pkg.volumeUuid;
23493        final String packageName = pkg.packageName;
23494        final ApplicationInfo app = pkg.applicationInfo;
23495        final int appId = UserHandle.getAppId(app.uid);
23496
23497        Preconditions.checkNotNull(app.seInfo);
23498
23499        long ceDataInode = -1;
23500        try {
23501            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23502                    appId, app.seInfo, app.targetSdkVersion);
23503        } catch (InstallerException e) {
23504            if (app.isSystemApp()) {
23505                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23506                        + ", but trying to recover: " + e);
23507                destroyAppDataLeafLIF(pkg, userId, flags);
23508                try {
23509                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23510                            appId, app.seInfo, app.targetSdkVersion);
23511                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23512                } catch (InstallerException e2) {
23513                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23514                }
23515            } else {
23516                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23517            }
23518        }
23519
23520        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23521            // TODO: mark this structure as dirty so we persist it!
23522            synchronized (mPackages) {
23523                final PackageSetting ps = mSettings.mPackages.get(packageName);
23524                if (ps != null) {
23525                    ps.setCeDataInode(ceDataInode, userId);
23526                }
23527            }
23528        }
23529
23530        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23531    }
23532
23533    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23534        if (pkg == null) {
23535            Slog.wtf(TAG, "Package was null!", new Throwable());
23536            return;
23537        }
23538        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23539        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23540        for (int i = 0; i < childCount; i++) {
23541            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23542        }
23543    }
23544
23545    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23546        final String volumeUuid = pkg.volumeUuid;
23547        final String packageName = pkg.packageName;
23548        final ApplicationInfo app = pkg.applicationInfo;
23549
23550        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23551            // Create a native library symlink only if we have native libraries
23552            // and if the native libraries are 32 bit libraries. We do not provide
23553            // this symlink for 64 bit libraries.
23554            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23555                final String nativeLibPath = app.nativeLibraryDir;
23556                try {
23557                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23558                            nativeLibPath, userId);
23559                } catch (InstallerException e) {
23560                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23561                }
23562            }
23563        }
23564    }
23565
23566    /**
23567     * For system apps on non-FBE devices, this method migrates any existing
23568     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23569     * requested by the app.
23570     */
23571    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23572        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23573                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23574            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23575                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23576            try {
23577                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23578                        storageTarget);
23579            } catch (InstallerException e) {
23580                logCriticalInfo(Log.WARN,
23581                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23582            }
23583            return true;
23584        } else {
23585            return false;
23586        }
23587    }
23588
23589    public PackageFreezer freezePackage(String packageName, String killReason) {
23590        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23591    }
23592
23593    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23594        return new PackageFreezer(packageName, userId, killReason);
23595    }
23596
23597    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23598            String killReason) {
23599        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23600    }
23601
23602    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23603            String killReason) {
23604        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23605            return new PackageFreezer();
23606        } else {
23607            return freezePackage(packageName, userId, killReason);
23608        }
23609    }
23610
23611    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23612            String killReason) {
23613        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23614    }
23615
23616    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23617            String killReason) {
23618        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23619            return new PackageFreezer();
23620        } else {
23621            return freezePackage(packageName, userId, killReason);
23622        }
23623    }
23624
23625    /**
23626     * Class that freezes and kills the given package upon creation, and
23627     * unfreezes it upon closing. This is typically used when doing surgery on
23628     * app code/data to prevent the app from running while you're working.
23629     */
23630    private class PackageFreezer implements AutoCloseable {
23631        private final String mPackageName;
23632        private final PackageFreezer[] mChildren;
23633
23634        private final boolean mWeFroze;
23635
23636        private final AtomicBoolean mClosed = new AtomicBoolean();
23637        private final CloseGuard mCloseGuard = CloseGuard.get();
23638
23639        /**
23640         * Create and return a stub freezer that doesn't actually do anything,
23641         * typically used when someone requested
23642         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23643         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23644         */
23645        public PackageFreezer() {
23646            mPackageName = null;
23647            mChildren = null;
23648            mWeFroze = false;
23649            mCloseGuard.open("close");
23650        }
23651
23652        public PackageFreezer(String packageName, int userId, String killReason) {
23653            synchronized (mPackages) {
23654                mPackageName = packageName;
23655                mWeFroze = mFrozenPackages.add(mPackageName);
23656
23657                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23658                if (ps != null) {
23659                    killApplication(ps.name, ps.appId, userId, killReason);
23660                }
23661
23662                final PackageParser.Package p = mPackages.get(packageName);
23663                if (p != null && p.childPackages != null) {
23664                    final int N = p.childPackages.size();
23665                    mChildren = new PackageFreezer[N];
23666                    for (int i = 0; i < N; i++) {
23667                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23668                                userId, killReason);
23669                    }
23670                } else {
23671                    mChildren = null;
23672                }
23673            }
23674            mCloseGuard.open("close");
23675        }
23676
23677        @Override
23678        protected void finalize() throws Throwable {
23679            try {
23680                if (mCloseGuard != null) {
23681                    mCloseGuard.warnIfOpen();
23682                }
23683
23684                close();
23685            } finally {
23686                super.finalize();
23687            }
23688        }
23689
23690        @Override
23691        public void close() {
23692            mCloseGuard.close();
23693            if (mClosed.compareAndSet(false, true)) {
23694                synchronized (mPackages) {
23695                    if (mWeFroze) {
23696                        mFrozenPackages.remove(mPackageName);
23697                    }
23698
23699                    if (mChildren != null) {
23700                        for (PackageFreezer freezer : mChildren) {
23701                            freezer.close();
23702                        }
23703                    }
23704                }
23705            }
23706        }
23707    }
23708
23709    /**
23710     * Verify that given package is currently frozen.
23711     */
23712    private void checkPackageFrozen(String packageName) {
23713        synchronized (mPackages) {
23714            if (!mFrozenPackages.contains(packageName)) {
23715                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23716            }
23717        }
23718    }
23719
23720    @Override
23721    public int movePackage(final String packageName, final String volumeUuid) {
23722        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23723
23724        final int callingUid = Binder.getCallingUid();
23725        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23726        final int moveId = mNextMoveId.getAndIncrement();
23727        mHandler.post(new Runnable() {
23728            @Override
23729            public void run() {
23730                try {
23731                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23732                } catch (PackageManagerException e) {
23733                    Slog.w(TAG, "Failed to move " + packageName, e);
23734                    mMoveCallbacks.notifyStatusChanged(moveId,
23735                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23736                }
23737            }
23738        });
23739        return moveId;
23740    }
23741
23742    private void movePackageInternal(final String packageName, final String volumeUuid,
23743            final int moveId, final int callingUid, UserHandle user)
23744                    throws PackageManagerException {
23745        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23746        final PackageManager pm = mContext.getPackageManager();
23747
23748        final boolean currentAsec;
23749        final String currentVolumeUuid;
23750        final File codeFile;
23751        final String installerPackageName;
23752        final String packageAbiOverride;
23753        final int appId;
23754        final String seinfo;
23755        final String label;
23756        final int targetSdkVersion;
23757        final PackageFreezer freezer;
23758        final int[] installedUserIds;
23759
23760        // reader
23761        synchronized (mPackages) {
23762            final PackageParser.Package pkg = mPackages.get(packageName);
23763            final PackageSetting ps = mSettings.mPackages.get(packageName);
23764            if (pkg == null
23765                    || ps == null
23766                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23767                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23768            }
23769            if (pkg.applicationInfo.isSystemApp()) {
23770                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23771                        "Cannot move system application");
23772            }
23773
23774            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23775            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23776                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23777            if (isInternalStorage && !allow3rdPartyOnInternal) {
23778                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23779                        "3rd party apps are not allowed on internal storage");
23780            }
23781
23782            if (pkg.applicationInfo.isExternalAsec()) {
23783                currentAsec = true;
23784                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23785            } else if (pkg.applicationInfo.isForwardLocked()) {
23786                currentAsec = true;
23787                currentVolumeUuid = "forward_locked";
23788            } else {
23789                currentAsec = false;
23790                currentVolumeUuid = ps.volumeUuid;
23791
23792                final File probe = new File(pkg.codePath);
23793                final File probeOat = new File(probe, "oat");
23794                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23795                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23796                            "Move only supported for modern cluster style installs");
23797                }
23798            }
23799
23800            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23801                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23802                        "Package already moved to " + volumeUuid);
23803            }
23804            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23805                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23806                        "Device admin cannot be moved");
23807            }
23808
23809            if (mFrozenPackages.contains(packageName)) {
23810                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23811                        "Failed to move already frozen package");
23812            }
23813
23814            codeFile = new File(pkg.codePath);
23815            installerPackageName = ps.installerPackageName;
23816            packageAbiOverride = ps.cpuAbiOverrideString;
23817            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23818            seinfo = pkg.applicationInfo.seInfo;
23819            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23820            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23821            freezer = freezePackage(packageName, "movePackageInternal");
23822            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23823        }
23824
23825        final Bundle extras = new Bundle();
23826        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23827        extras.putString(Intent.EXTRA_TITLE, label);
23828        mMoveCallbacks.notifyCreated(moveId, extras);
23829
23830        int installFlags;
23831        final boolean moveCompleteApp;
23832        final File measurePath;
23833
23834        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23835            installFlags = INSTALL_INTERNAL;
23836            moveCompleteApp = !currentAsec;
23837            measurePath = Environment.getDataAppDirectory(volumeUuid);
23838        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23839            installFlags = INSTALL_EXTERNAL;
23840            moveCompleteApp = false;
23841            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23842        } else {
23843            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23844            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23845                    || !volume.isMountedWritable()) {
23846                freezer.close();
23847                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23848                        "Move location not mounted private volume");
23849            }
23850
23851            Preconditions.checkState(!currentAsec);
23852
23853            installFlags = INSTALL_INTERNAL;
23854            moveCompleteApp = true;
23855            measurePath = Environment.getDataAppDirectory(volumeUuid);
23856        }
23857
23858        final PackageStats stats = new PackageStats(null, -1);
23859        synchronized (mInstaller) {
23860            for (int userId : installedUserIds) {
23861                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23862                    freezer.close();
23863                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23864                            "Failed to measure package size");
23865                }
23866            }
23867        }
23868
23869        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23870                + stats.dataSize);
23871
23872        final long startFreeBytes = measurePath.getUsableSpace();
23873        final long sizeBytes;
23874        if (moveCompleteApp) {
23875            sizeBytes = stats.codeSize + stats.dataSize;
23876        } else {
23877            sizeBytes = stats.codeSize;
23878        }
23879
23880        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23881            freezer.close();
23882            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23883                    "Not enough free space to move");
23884        }
23885
23886        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23887
23888        final CountDownLatch installedLatch = new CountDownLatch(1);
23889        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23890            @Override
23891            public void onUserActionRequired(Intent intent) throws RemoteException {
23892                throw new IllegalStateException();
23893            }
23894
23895            @Override
23896            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23897                    Bundle extras) throws RemoteException {
23898                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23899                        + PackageManager.installStatusToString(returnCode, msg));
23900
23901                installedLatch.countDown();
23902                freezer.close();
23903
23904                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23905                switch (status) {
23906                    case PackageInstaller.STATUS_SUCCESS:
23907                        mMoveCallbacks.notifyStatusChanged(moveId,
23908                                PackageManager.MOVE_SUCCEEDED);
23909                        break;
23910                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23911                        mMoveCallbacks.notifyStatusChanged(moveId,
23912                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23913                        break;
23914                    default:
23915                        mMoveCallbacks.notifyStatusChanged(moveId,
23916                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23917                        break;
23918                }
23919            }
23920        };
23921
23922        final MoveInfo move;
23923        if (moveCompleteApp) {
23924            // Kick off a thread to report progress estimates
23925            new Thread() {
23926                @Override
23927                public void run() {
23928                    while (true) {
23929                        try {
23930                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23931                                break;
23932                            }
23933                        } catch (InterruptedException ignored) {
23934                        }
23935
23936                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23937                        final int progress = 10 + (int) MathUtils.constrain(
23938                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23939                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23940                    }
23941                }
23942            }.start();
23943
23944            final String dataAppName = codeFile.getName();
23945            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23946                    dataAppName, appId, seinfo, targetSdkVersion);
23947        } else {
23948            move = null;
23949        }
23950
23951        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23952
23953        final Message msg = mHandler.obtainMessage(INIT_COPY);
23954        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23955        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23956                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23957                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23958                PackageManager.INSTALL_REASON_UNKNOWN);
23959        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23960        msg.obj = params;
23961
23962        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23963                System.identityHashCode(msg.obj));
23964        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23965                System.identityHashCode(msg.obj));
23966
23967        mHandler.sendMessage(msg);
23968    }
23969
23970    @Override
23971    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23972        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23973
23974        final int realMoveId = mNextMoveId.getAndIncrement();
23975        final Bundle extras = new Bundle();
23976        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23977        mMoveCallbacks.notifyCreated(realMoveId, extras);
23978
23979        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23980            @Override
23981            public void onCreated(int moveId, Bundle extras) {
23982                // Ignored
23983            }
23984
23985            @Override
23986            public void onStatusChanged(int moveId, int status, long estMillis) {
23987                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23988            }
23989        };
23990
23991        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23992        storage.setPrimaryStorageUuid(volumeUuid, callback);
23993        return realMoveId;
23994    }
23995
23996    @Override
23997    public int getMoveStatus(int moveId) {
23998        mContext.enforceCallingOrSelfPermission(
23999                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24000        return mMoveCallbacks.mLastStatus.get(moveId);
24001    }
24002
24003    @Override
24004    public void registerMoveCallback(IPackageMoveObserver callback) {
24005        mContext.enforceCallingOrSelfPermission(
24006                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24007        mMoveCallbacks.register(callback);
24008    }
24009
24010    @Override
24011    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24012        mContext.enforceCallingOrSelfPermission(
24013                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24014        mMoveCallbacks.unregister(callback);
24015    }
24016
24017    @Override
24018    public boolean setInstallLocation(int loc) {
24019        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24020                null);
24021        if (getInstallLocation() == loc) {
24022            return true;
24023        }
24024        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24025                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24026            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24027                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24028            return true;
24029        }
24030        return false;
24031   }
24032
24033    @Override
24034    public int getInstallLocation() {
24035        // allow instant app access
24036        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24037                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24038                PackageHelper.APP_INSTALL_AUTO);
24039    }
24040
24041    /** Called by UserManagerService */
24042    void cleanUpUser(UserManagerService userManager, int userHandle) {
24043        synchronized (mPackages) {
24044            mDirtyUsers.remove(userHandle);
24045            mUserNeedsBadging.delete(userHandle);
24046            mSettings.removeUserLPw(userHandle);
24047            mPendingBroadcasts.remove(userHandle);
24048            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24049            removeUnusedPackagesLPw(userManager, userHandle);
24050        }
24051    }
24052
24053    /**
24054     * We're removing userHandle and would like to remove any downloaded packages
24055     * that are no longer in use by any other user.
24056     * @param userHandle the user being removed
24057     */
24058    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24059        final boolean DEBUG_CLEAN_APKS = false;
24060        int [] users = userManager.getUserIds();
24061        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24062        while (psit.hasNext()) {
24063            PackageSetting ps = psit.next();
24064            if (ps.pkg == null) {
24065                continue;
24066            }
24067            final String packageName = ps.pkg.packageName;
24068            // Skip over if system app
24069            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24070                continue;
24071            }
24072            if (DEBUG_CLEAN_APKS) {
24073                Slog.i(TAG, "Checking package " + packageName);
24074            }
24075            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24076            if (keep) {
24077                if (DEBUG_CLEAN_APKS) {
24078                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24079                }
24080            } else {
24081                for (int i = 0; i < users.length; i++) {
24082                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24083                        keep = true;
24084                        if (DEBUG_CLEAN_APKS) {
24085                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24086                                    + users[i]);
24087                        }
24088                        break;
24089                    }
24090                }
24091            }
24092            if (!keep) {
24093                if (DEBUG_CLEAN_APKS) {
24094                    Slog.i(TAG, "  Removing package " + packageName);
24095                }
24096                mHandler.post(new Runnable() {
24097                    public void run() {
24098                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24099                                userHandle, 0);
24100                    } //end run
24101                });
24102            }
24103        }
24104    }
24105
24106    /** Called by UserManagerService */
24107    void createNewUser(int userId, String[] disallowedPackages) {
24108        synchronized (mInstallLock) {
24109            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24110        }
24111        synchronized (mPackages) {
24112            scheduleWritePackageRestrictionsLocked(userId);
24113            scheduleWritePackageListLocked(userId);
24114            applyFactoryDefaultBrowserLPw(userId);
24115            primeDomainVerificationsLPw(userId);
24116        }
24117    }
24118
24119    void onNewUserCreated(final int userId) {
24120        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24121        // If permission review for legacy apps is required, we represent
24122        // dagerous permissions for such apps as always granted runtime
24123        // permissions to keep per user flag state whether review is needed.
24124        // Hence, if a new user is added we have to propagate dangerous
24125        // permission grants for these legacy apps.
24126        if (mPermissionReviewRequired) {
24127            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24128                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24129        }
24130    }
24131
24132    @Override
24133    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24134        mContext.enforceCallingOrSelfPermission(
24135                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24136                "Only package verification agents can read the verifier device identity");
24137
24138        synchronized (mPackages) {
24139            return mSettings.getVerifierDeviceIdentityLPw();
24140        }
24141    }
24142
24143    @Override
24144    public void setPermissionEnforced(String permission, boolean enforced) {
24145        // TODO: Now that we no longer change GID for storage, this should to away.
24146        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24147                "setPermissionEnforced");
24148        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24149            synchronized (mPackages) {
24150                if (mSettings.mReadExternalStorageEnforced == null
24151                        || mSettings.mReadExternalStorageEnforced != enforced) {
24152                    mSettings.mReadExternalStorageEnforced = enforced;
24153                    mSettings.writeLPr();
24154                }
24155            }
24156            // kill any non-foreground processes so we restart them and
24157            // grant/revoke the GID.
24158            final IActivityManager am = ActivityManager.getService();
24159            if (am != null) {
24160                final long token = Binder.clearCallingIdentity();
24161                try {
24162                    am.killProcessesBelowForeground("setPermissionEnforcement");
24163                } catch (RemoteException e) {
24164                } finally {
24165                    Binder.restoreCallingIdentity(token);
24166                }
24167            }
24168        } else {
24169            throw new IllegalArgumentException("No selective enforcement for " + permission);
24170        }
24171    }
24172
24173    @Override
24174    @Deprecated
24175    public boolean isPermissionEnforced(String permission) {
24176        // allow instant applications
24177        return true;
24178    }
24179
24180    @Override
24181    public boolean isStorageLow() {
24182        // allow instant applications
24183        final long token = Binder.clearCallingIdentity();
24184        try {
24185            final DeviceStorageMonitorInternal
24186                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24187            if (dsm != null) {
24188                return dsm.isMemoryLow();
24189            } else {
24190                return false;
24191            }
24192        } finally {
24193            Binder.restoreCallingIdentity(token);
24194        }
24195    }
24196
24197    @Override
24198    public IPackageInstaller getPackageInstaller() {
24199        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24200            return null;
24201        }
24202        return mInstallerService;
24203    }
24204
24205    private boolean userNeedsBadging(int userId) {
24206        int index = mUserNeedsBadging.indexOfKey(userId);
24207        if (index < 0) {
24208            final UserInfo userInfo;
24209            final long token = Binder.clearCallingIdentity();
24210            try {
24211                userInfo = sUserManager.getUserInfo(userId);
24212            } finally {
24213                Binder.restoreCallingIdentity(token);
24214            }
24215            final boolean b;
24216            if (userInfo != null && userInfo.isManagedProfile()) {
24217                b = true;
24218            } else {
24219                b = false;
24220            }
24221            mUserNeedsBadging.put(userId, b);
24222            return b;
24223        }
24224        return mUserNeedsBadging.valueAt(index);
24225    }
24226
24227    @Override
24228    public KeySet getKeySetByAlias(String packageName, String alias) {
24229        if (packageName == null || alias == null) {
24230            return null;
24231        }
24232        synchronized(mPackages) {
24233            final PackageParser.Package pkg = mPackages.get(packageName);
24234            if (pkg == null) {
24235                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24236                throw new IllegalArgumentException("Unknown package: " + packageName);
24237            }
24238            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24239            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24240                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24241                throw new IllegalArgumentException("Unknown package: " + packageName);
24242            }
24243            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24244            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24245        }
24246    }
24247
24248    @Override
24249    public KeySet getSigningKeySet(String packageName) {
24250        if (packageName == null) {
24251            return null;
24252        }
24253        synchronized(mPackages) {
24254            final int callingUid = Binder.getCallingUid();
24255            final int callingUserId = UserHandle.getUserId(callingUid);
24256            final PackageParser.Package pkg = mPackages.get(packageName);
24257            if (pkg == null) {
24258                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24259                throw new IllegalArgumentException("Unknown package: " + packageName);
24260            }
24261            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24262            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24263                // filter and pretend the package doesn't exist
24264                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24265                        + ", uid:" + callingUid);
24266                throw new IllegalArgumentException("Unknown package: " + packageName);
24267            }
24268            if (pkg.applicationInfo.uid != callingUid
24269                    && Process.SYSTEM_UID != callingUid) {
24270                throw new SecurityException("May not access signing KeySet of other apps.");
24271            }
24272            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24273            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24274        }
24275    }
24276
24277    @Override
24278    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24279        final int callingUid = Binder.getCallingUid();
24280        if (getInstantAppPackageName(callingUid) != null) {
24281            return false;
24282        }
24283        if (packageName == null || ks == null) {
24284            return false;
24285        }
24286        synchronized(mPackages) {
24287            final PackageParser.Package pkg = mPackages.get(packageName);
24288            if (pkg == null
24289                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24290                            UserHandle.getUserId(callingUid))) {
24291                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24292                throw new IllegalArgumentException("Unknown package: " + packageName);
24293            }
24294            IBinder ksh = ks.getToken();
24295            if (ksh instanceof KeySetHandle) {
24296                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24297                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24298            }
24299            return false;
24300        }
24301    }
24302
24303    @Override
24304    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24305        final int callingUid = Binder.getCallingUid();
24306        if (getInstantAppPackageName(callingUid) != null) {
24307            return false;
24308        }
24309        if (packageName == null || ks == null) {
24310            return false;
24311        }
24312        synchronized(mPackages) {
24313            final PackageParser.Package pkg = mPackages.get(packageName);
24314            if (pkg == null
24315                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24316                            UserHandle.getUserId(callingUid))) {
24317                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24318                throw new IllegalArgumentException("Unknown package: " + packageName);
24319            }
24320            IBinder ksh = ks.getToken();
24321            if (ksh instanceof KeySetHandle) {
24322                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24323                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24324            }
24325            return false;
24326        }
24327    }
24328
24329    private void deletePackageIfUnusedLPr(final String packageName) {
24330        PackageSetting ps = mSettings.mPackages.get(packageName);
24331        if (ps == null) {
24332            return;
24333        }
24334        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24335            // TODO Implement atomic delete if package is unused
24336            // It is currently possible that the package will be deleted even if it is installed
24337            // after this method returns.
24338            mHandler.post(new Runnable() {
24339                public void run() {
24340                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24341                            0, PackageManager.DELETE_ALL_USERS);
24342                }
24343            });
24344        }
24345    }
24346
24347    /**
24348     * Check and throw if the given before/after packages would be considered a
24349     * downgrade.
24350     */
24351    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24352            throws PackageManagerException {
24353        if (after.versionCode < before.mVersionCode) {
24354            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24355                    "Update version code " + after.versionCode + " is older than current "
24356                    + before.mVersionCode);
24357        } else if (after.versionCode == before.mVersionCode) {
24358            if (after.baseRevisionCode < before.baseRevisionCode) {
24359                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24360                        "Update base revision code " + after.baseRevisionCode
24361                        + " is older than current " + before.baseRevisionCode);
24362            }
24363
24364            if (!ArrayUtils.isEmpty(after.splitNames)) {
24365                for (int i = 0; i < after.splitNames.length; i++) {
24366                    final String splitName = after.splitNames[i];
24367                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24368                    if (j != -1) {
24369                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24370                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24371                                    "Update split " + splitName + " revision code "
24372                                    + after.splitRevisionCodes[i] + " is older than current "
24373                                    + before.splitRevisionCodes[j]);
24374                        }
24375                    }
24376                }
24377            }
24378        }
24379    }
24380
24381    private static class MoveCallbacks extends Handler {
24382        private static final int MSG_CREATED = 1;
24383        private static final int MSG_STATUS_CHANGED = 2;
24384
24385        private final RemoteCallbackList<IPackageMoveObserver>
24386                mCallbacks = new RemoteCallbackList<>();
24387
24388        private final SparseIntArray mLastStatus = new SparseIntArray();
24389
24390        public MoveCallbacks(Looper looper) {
24391            super(looper);
24392        }
24393
24394        public void register(IPackageMoveObserver callback) {
24395            mCallbacks.register(callback);
24396        }
24397
24398        public void unregister(IPackageMoveObserver callback) {
24399            mCallbacks.unregister(callback);
24400        }
24401
24402        @Override
24403        public void handleMessage(Message msg) {
24404            final SomeArgs args = (SomeArgs) msg.obj;
24405            final int n = mCallbacks.beginBroadcast();
24406            for (int i = 0; i < n; i++) {
24407                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24408                try {
24409                    invokeCallback(callback, msg.what, args);
24410                } catch (RemoteException ignored) {
24411                }
24412            }
24413            mCallbacks.finishBroadcast();
24414            args.recycle();
24415        }
24416
24417        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24418                throws RemoteException {
24419            switch (what) {
24420                case MSG_CREATED: {
24421                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24422                    break;
24423                }
24424                case MSG_STATUS_CHANGED: {
24425                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24426                    break;
24427                }
24428            }
24429        }
24430
24431        private void notifyCreated(int moveId, Bundle extras) {
24432            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24433
24434            final SomeArgs args = SomeArgs.obtain();
24435            args.argi1 = moveId;
24436            args.arg2 = extras;
24437            obtainMessage(MSG_CREATED, args).sendToTarget();
24438        }
24439
24440        private void notifyStatusChanged(int moveId, int status) {
24441            notifyStatusChanged(moveId, status, -1);
24442        }
24443
24444        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24445            Slog.v(TAG, "Move " + moveId + " status " + status);
24446
24447            final SomeArgs args = SomeArgs.obtain();
24448            args.argi1 = moveId;
24449            args.argi2 = status;
24450            args.arg3 = estMillis;
24451            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24452
24453            synchronized (mLastStatus) {
24454                mLastStatus.put(moveId, status);
24455            }
24456        }
24457    }
24458
24459    private final static class OnPermissionChangeListeners extends Handler {
24460        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24461
24462        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24463                new RemoteCallbackList<>();
24464
24465        public OnPermissionChangeListeners(Looper looper) {
24466            super(looper);
24467        }
24468
24469        @Override
24470        public void handleMessage(Message msg) {
24471            switch (msg.what) {
24472                case MSG_ON_PERMISSIONS_CHANGED: {
24473                    final int uid = msg.arg1;
24474                    handleOnPermissionsChanged(uid);
24475                } break;
24476            }
24477        }
24478
24479        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24480            mPermissionListeners.register(listener);
24481
24482        }
24483
24484        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24485            mPermissionListeners.unregister(listener);
24486        }
24487
24488        public void onPermissionsChanged(int uid) {
24489            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24490                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24491            }
24492        }
24493
24494        private void handleOnPermissionsChanged(int uid) {
24495            final int count = mPermissionListeners.beginBroadcast();
24496            try {
24497                for (int i = 0; i < count; i++) {
24498                    IOnPermissionsChangeListener callback = mPermissionListeners
24499                            .getBroadcastItem(i);
24500                    try {
24501                        callback.onPermissionsChanged(uid);
24502                    } catch (RemoteException e) {
24503                        Log.e(TAG, "Permission listener is dead", e);
24504                    }
24505                }
24506            } finally {
24507                mPermissionListeners.finishBroadcast();
24508            }
24509        }
24510    }
24511
24512    private class PackageManagerInternalImpl extends PackageManagerInternal {
24513        @Override
24514        public void setLocationPackagesProvider(PackagesProvider provider) {
24515            synchronized (mPackages) {
24516                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24517            }
24518        }
24519
24520        @Override
24521        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24522            synchronized (mPackages) {
24523                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24524            }
24525        }
24526
24527        @Override
24528        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24529            synchronized (mPackages) {
24530                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24531            }
24532        }
24533
24534        @Override
24535        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24536            synchronized (mPackages) {
24537                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24538            }
24539        }
24540
24541        @Override
24542        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24543            synchronized (mPackages) {
24544                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24545            }
24546        }
24547
24548        @Override
24549        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24550            synchronized (mPackages) {
24551                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24552            }
24553        }
24554
24555        @Override
24556        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24557            synchronized (mPackages) {
24558                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24559                        packageName, userId);
24560            }
24561        }
24562
24563        @Override
24564        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24565            synchronized (mPackages) {
24566                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24567                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24568                        packageName, userId);
24569            }
24570        }
24571
24572        @Override
24573        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24574            synchronized (mPackages) {
24575                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24576                        packageName, userId);
24577            }
24578        }
24579
24580        @Override
24581        public void setKeepUninstalledPackages(final List<String> packageList) {
24582            Preconditions.checkNotNull(packageList);
24583            List<String> removedFromList = null;
24584            synchronized (mPackages) {
24585                if (mKeepUninstalledPackages != null) {
24586                    final int packagesCount = mKeepUninstalledPackages.size();
24587                    for (int i = 0; i < packagesCount; i++) {
24588                        String oldPackage = mKeepUninstalledPackages.get(i);
24589                        if (packageList != null && packageList.contains(oldPackage)) {
24590                            continue;
24591                        }
24592                        if (removedFromList == null) {
24593                            removedFromList = new ArrayList<>();
24594                        }
24595                        removedFromList.add(oldPackage);
24596                    }
24597                }
24598                mKeepUninstalledPackages = new ArrayList<>(packageList);
24599                if (removedFromList != null) {
24600                    final int removedCount = removedFromList.size();
24601                    for (int i = 0; i < removedCount; i++) {
24602                        deletePackageIfUnusedLPr(removedFromList.get(i));
24603                    }
24604                }
24605            }
24606        }
24607
24608        @Override
24609        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24610            synchronized (mPackages) {
24611                // If we do not support permission review, done.
24612                if (!mPermissionReviewRequired) {
24613                    return false;
24614                }
24615
24616                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24617                if (packageSetting == null) {
24618                    return false;
24619                }
24620
24621                // Permission review applies only to apps not supporting the new permission model.
24622                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24623                    return false;
24624                }
24625
24626                // Legacy apps have the permission and get user consent on launch.
24627                PermissionsState permissionsState = packageSetting.getPermissionsState();
24628                return permissionsState.isPermissionReviewRequired(userId);
24629            }
24630        }
24631
24632        @Override
24633        public PackageInfo getPackageInfo(
24634                String packageName, int flags, int filterCallingUid, int userId) {
24635            return PackageManagerService.this
24636                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24637                            flags, filterCallingUid, userId);
24638        }
24639
24640        @Override
24641        public ApplicationInfo getApplicationInfo(
24642                String packageName, int flags, int filterCallingUid, int userId) {
24643            return PackageManagerService.this
24644                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24645        }
24646
24647        @Override
24648        public ActivityInfo getActivityInfo(
24649                ComponentName component, int flags, int filterCallingUid, int userId) {
24650            return PackageManagerService.this
24651                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24652        }
24653
24654        @Override
24655        public List<ResolveInfo> queryIntentActivities(
24656                Intent intent, int flags, int filterCallingUid, int userId) {
24657            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24658            return PackageManagerService.this
24659                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24660                            userId, false /*resolveForStart*/);
24661        }
24662
24663        @Override
24664        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24665                int userId) {
24666            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24667        }
24668
24669        @Override
24670        public void setDeviceAndProfileOwnerPackages(
24671                int deviceOwnerUserId, String deviceOwnerPackage,
24672                SparseArray<String> profileOwnerPackages) {
24673            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24674                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24675        }
24676
24677        @Override
24678        public boolean isPackageDataProtected(int userId, String packageName) {
24679            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24680        }
24681
24682        @Override
24683        public boolean isPackageEphemeral(int userId, String packageName) {
24684            synchronized (mPackages) {
24685                final PackageSetting ps = mSettings.mPackages.get(packageName);
24686                return ps != null ? ps.getInstantApp(userId) : false;
24687            }
24688        }
24689
24690        @Override
24691        public boolean wasPackageEverLaunched(String packageName, int userId) {
24692            synchronized (mPackages) {
24693                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24694            }
24695        }
24696
24697        @Override
24698        public void grantRuntimePermission(String packageName, String name, int userId,
24699                boolean overridePolicy) {
24700            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24701                    overridePolicy);
24702        }
24703
24704        @Override
24705        public void revokeRuntimePermission(String packageName, String name, int userId,
24706                boolean overridePolicy) {
24707            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24708                    overridePolicy);
24709        }
24710
24711        @Override
24712        public String getNameForUid(int uid) {
24713            return PackageManagerService.this.getNameForUid(uid);
24714        }
24715
24716        @Override
24717        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24718                Intent origIntent, String resolvedType, String callingPackage,
24719                Bundle verificationBundle, int userId) {
24720            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24721                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24722                    userId);
24723        }
24724
24725        @Override
24726        public void grantEphemeralAccess(int userId, Intent intent,
24727                int targetAppId, int ephemeralAppId) {
24728            synchronized (mPackages) {
24729                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24730                        targetAppId, ephemeralAppId);
24731            }
24732        }
24733
24734        @Override
24735        public boolean isInstantAppInstallerComponent(ComponentName component) {
24736            synchronized (mPackages) {
24737                return mInstantAppInstallerActivity != null
24738                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24739            }
24740        }
24741
24742        @Override
24743        public void pruneInstantApps() {
24744            mInstantAppRegistry.pruneInstantApps();
24745        }
24746
24747        @Override
24748        public String getSetupWizardPackageName() {
24749            return mSetupWizardPackage;
24750        }
24751
24752        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24753            if (policy != null) {
24754                mExternalSourcesPolicy = policy;
24755            }
24756        }
24757
24758        @Override
24759        public boolean isPackagePersistent(String packageName) {
24760            synchronized (mPackages) {
24761                PackageParser.Package pkg = mPackages.get(packageName);
24762                return pkg != null
24763                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24764                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24765                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24766                        : false;
24767            }
24768        }
24769
24770        @Override
24771        public List<PackageInfo> getOverlayPackages(int userId) {
24772            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24773            synchronized (mPackages) {
24774                for (PackageParser.Package p : mPackages.values()) {
24775                    if (p.mOverlayTarget != null) {
24776                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24777                        if (pkg != null) {
24778                            overlayPackages.add(pkg);
24779                        }
24780                    }
24781                }
24782            }
24783            return overlayPackages;
24784        }
24785
24786        @Override
24787        public List<String> getTargetPackageNames(int userId) {
24788            List<String> targetPackages = new ArrayList<>();
24789            synchronized (mPackages) {
24790                for (PackageParser.Package p : mPackages.values()) {
24791                    if (p.mOverlayTarget == null) {
24792                        targetPackages.add(p.packageName);
24793                    }
24794                }
24795            }
24796            return targetPackages;
24797        }
24798
24799        @Override
24800        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24801                @Nullable List<String> overlayPackageNames) {
24802            synchronized (mPackages) {
24803                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24804                    Slog.e(TAG, "failed to find package " + targetPackageName);
24805                    return false;
24806                }
24807                ArrayList<String> overlayPaths = null;
24808                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24809                    final int N = overlayPackageNames.size();
24810                    overlayPaths = new ArrayList<>(N);
24811                    for (int i = 0; i < N; i++) {
24812                        final String packageName = overlayPackageNames.get(i);
24813                        final PackageParser.Package pkg = mPackages.get(packageName);
24814                        if (pkg == null) {
24815                            Slog.e(TAG, "failed to find package " + packageName);
24816                            return false;
24817                        }
24818                        overlayPaths.add(pkg.baseCodePath);
24819                    }
24820                }
24821
24822                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24823                ps.setOverlayPaths(overlayPaths, userId);
24824                return true;
24825            }
24826        }
24827
24828        @Override
24829        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24830                int flags, int userId) {
24831            return resolveIntentInternal(
24832                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24833        }
24834
24835        @Override
24836        public ResolveInfo resolveService(Intent intent, String resolvedType,
24837                int flags, int userId, int callingUid) {
24838            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24839        }
24840
24841        @Override
24842        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24843            synchronized (mPackages) {
24844                mIsolatedOwners.put(isolatedUid, ownerUid);
24845            }
24846        }
24847
24848        @Override
24849        public void removeIsolatedUid(int isolatedUid) {
24850            synchronized (mPackages) {
24851                mIsolatedOwners.delete(isolatedUid);
24852            }
24853        }
24854
24855        @Override
24856        public int getUidTargetSdkVersion(int uid) {
24857            synchronized (mPackages) {
24858                return getUidTargetSdkVersionLockedLPr(uid);
24859            }
24860        }
24861
24862        @Override
24863        public boolean canAccessInstantApps(int callingUid, int userId) {
24864            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24865        }
24866    }
24867
24868    @Override
24869    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24870        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24871        synchronized (mPackages) {
24872            final long identity = Binder.clearCallingIdentity();
24873            try {
24874                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24875                        packageNames, userId);
24876            } finally {
24877                Binder.restoreCallingIdentity(identity);
24878            }
24879        }
24880    }
24881
24882    @Override
24883    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24884        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24885        synchronized (mPackages) {
24886            final long identity = Binder.clearCallingIdentity();
24887            try {
24888                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24889                        packageNames, userId);
24890            } finally {
24891                Binder.restoreCallingIdentity(identity);
24892            }
24893        }
24894    }
24895
24896    private static void enforceSystemOrPhoneCaller(String tag) {
24897        int callingUid = Binder.getCallingUid();
24898        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24899            throw new SecurityException(
24900                    "Cannot call " + tag + " from UID " + callingUid);
24901        }
24902    }
24903
24904    boolean isHistoricalPackageUsageAvailable() {
24905        return mPackageUsage.isHistoricalPackageUsageAvailable();
24906    }
24907
24908    /**
24909     * Return a <b>copy</b> of the collection of packages known to the package manager.
24910     * @return A copy of the values of mPackages.
24911     */
24912    Collection<PackageParser.Package> getPackages() {
24913        synchronized (mPackages) {
24914            return new ArrayList<>(mPackages.values());
24915        }
24916    }
24917
24918    /**
24919     * Logs process start information (including base APK hash) to the security log.
24920     * @hide
24921     */
24922    @Override
24923    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24924            String apkFile, int pid) {
24925        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24926            return;
24927        }
24928        if (!SecurityLog.isLoggingEnabled()) {
24929            return;
24930        }
24931        Bundle data = new Bundle();
24932        data.putLong("startTimestamp", System.currentTimeMillis());
24933        data.putString("processName", processName);
24934        data.putInt("uid", uid);
24935        data.putString("seinfo", seinfo);
24936        data.putString("apkFile", apkFile);
24937        data.putInt("pid", pid);
24938        Message msg = mProcessLoggingHandler.obtainMessage(
24939                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24940        msg.setData(data);
24941        mProcessLoggingHandler.sendMessage(msg);
24942    }
24943
24944    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24945        return mCompilerStats.getPackageStats(pkgName);
24946    }
24947
24948    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24949        return getOrCreateCompilerPackageStats(pkg.packageName);
24950    }
24951
24952    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24953        return mCompilerStats.getOrCreatePackageStats(pkgName);
24954    }
24955
24956    public void deleteCompilerPackageStats(String pkgName) {
24957        mCompilerStats.deletePackageStats(pkgName);
24958    }
24959
24960    @Override
24961    public int getInstallReason(String packageName, int userId) {
24962        final int callingUid = Binder.getCallingUid();
24963        enforceCrossUserPermission(callingUid, userId,
24964                true /* requireFullPermission */, false /* checkShell */,
24965                "get install reason");
24966        synchronized (mPackages) {
24967            final PackageSetting ps = mSettings.mPackages.get(packageName);
24968            if (filterAppAccessLPr(ps, callingUid, userId)) {
24969                return PackageManager.INSTALL_REASON_UNKNOWN;
24970            }
24971            if (ps != null) {
24972                return ps.getInstallReason(userId);
24973            }
24974        }
24975        return PackageManager.INSTALL_REASON_UNKNOWN;
24976    }
24977
24978    @Override
24979    public boolean canRequestPackageInstalls(String packageName, int userId) {
24980        return canRequestPackageInstallsInternal(packageName, 0, userId,
24981                true /* throwIfPermNotDeclared*/);
24982    }
24983
24984    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24985            boolean throwIfPermNotDeclared) {
24986        int callingUid = Binder.getCallingUid();
24987        int uid = getPackageUid(packageName, 0, userId);
24988        if (callingUid != uid && callingUid != Process.ROOT_UID
24989                && callingUid != Process.SYSTEM_UID) {
24990            throw new SecurityException(
24991                    "Caller uid " + callingUid + " does not own package " + packageName);
24992        }
24993        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24994        if (info == null) {
24995            return false;
24996        }
24997        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24998            return false;
24999        }
25000        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25001        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25002        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25003            if (throwIfPermNotDeclared) {
25004                throw new SecurityException("Need to declare " + appOpPermission
25005                        + " to call this api");
25006            } else {
25007                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25008                return false;
25009            }
25010        }
25011        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25012            return false;
25013        }
25014        if (mExternalSourcesPolicy != null) {
25015            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25016            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25017                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25018            }
25019        }
25020        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25021    }
25022
25023    @Override
25024    public ComponentName getInstantAppResolverSettingsComponent() {
25025        return mInstantAppResolverSettingsComponent;
25026    }
25027
25028    @Override
25029    public ComponentName getInstantAppInstallerComponent() {
25030        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25031            return null;
25032        }
25033        return mInstantAppInstallerActivity == null
25034                ? null : mInstantAppInstallerActivity.getComponentName();
25035    }
25036
25037    @Override
25038    public String getInstantAppAndroidId(String packageName, int userId) {
25039        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25040                "getInstantAppAndroidId");
25041        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25042                true /* requireFullPermission */, false /* checkShell */,
25043                "getInstantAppAndroidId");
25044        // Make sure the target is an Instant App.
25045        if (!isInstantApp(packageName, userId)) {
25046            return null;
25047        }
25048        synchronized (mPackages) {
25049            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25050        }
25051    }
25052
25053    boolean canHaveOatDir(String packageName) {
25054        synchronized (mPackages) {
25055            PackageParser.Package p = mPackages.get(packageName);
25056            if (p == null) {
25057                return false;
25058            }
25059            return p.canHaveOatDir();
25060        }
25061    }
25062
25063    private String getOatDir(PackageParser.Package pkg) {
25064        if (!pkg.canHaveOatDir()) {
25065            return null;
25066        }
25067        File codePath = new File(pkg.codePath);
25068        if (codePath.isDirectory()) {
25069            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25070        }
25071        return null;
25072    }
25073
25074    void deleteOatArtifactsOfPackage(String packageName) {
25075        final String[] instructionSets;
25076        final List<String> codePaths;
25077        final String oatDir;
25078        final PackageParser.Package pkg;
25079        synchronized (mPackages) {
25080            pkg = mPackages.get(packageName);
25081        }
25082        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25083        codePaths = pkg.getAllCodePaths();
25084        oatDir = getOatDir(pkg);
25085
25086        for (String codePath : codePaths) {
25087            for (String isa : instructionSets) {
25088                try {
25089                    mInstaller.deleteOdex(codePath, isa, oatDir);
25090                } catch (InstallerException e) {
25091                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25092                }
25093            }
25094        }
25095    }
25096
25097    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25098        Set<String> unusedPackages = new HashSet<>();
25099        long currentTimeInMillis = System.currentTimeMillis();
25100        synchronized (mPackages) {
25101            for (PackageParser.Package pkg : mPackages.values()) {
25102                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25103                if (ps == null) {
25104                    continue;
25105                }
25106                PackageDexUsage.PackageUseInfo packageUseInfo =
25107                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25108                if (PackageManagerServiceUtils
25109                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25110                                downgradeTimeThresholdMillis, packageUseInfo,
25111                                pkg.getLatestPackageUseTimeInMills(),
25112                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25113                    unusedPackages.add(pkg.packageName);
25114                }
25115            }
25116        }
25117        return unusedPackages;
25118    }
25119}
25120
25121interface PackageSender {
25122    void sendPackageBroadcast(final String action, final String pkg,
25123        final Bundle extras, final int flags, final String targetPkg,
25124        final IIntentReceiver finishedReceiver, final int[] userIds);
25125    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25126        int appId, int... userIds);
25127}
25128