PackageManagerService.java revision 09c0ef3cf95118c31e3d07b9037da8ea0d2e066e
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_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
103import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
104
105import android.Manifest;
106import android.annotation.IntDef;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.AuxiliaryResolveInfo;
130import android.content.pm.ChangedPackages;
131import android.content.pm.FallbackCategoryProvider;
132import android.content.pm.FeatureInfo;
133import android.content.pm.IOnPermissionsChangeListener;
134import android.content.pm.IPackageDataObserver;
135import android.content.pm.IPackageDeleteObserver;
136import android.content.pm.IPackageDeleteObserver2;
137import android.content.pm.IPackageInstallObserver2;
138import android.content.pm.IPackageInstaller;
139import android.content.pm.IPackageManager;
140import android.content.pm.IPackageMoveObserver;
141import android.content.pm.IPackageStatsObserver;
142import android.content.pm.InstantAppInfo;
143import android.content.pm.InstantAppRequest;
144import android.content.pm.InstantAppResolveInfo;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.database.ContentObserver;
175import android.graphics.Bitmap;
176import android.hardware.display.DisplayManager;
177import android.net.Uri;
178import android.os.Binder;
179import android.os.Build;
180import android.os.Bundle;
181import android.os.Debug;
182import android.os.Environment;
183import android.os.Environment.UserEnvironment;
184import android.os.FileUtils;
185import android.os.Handler;
186import android.os.IBinder;
187import android.os.Looper;
188import android.os.Message;
189import android.os.Parcel;
190import android.os.ParcelFileDescriptor;
191import android.os.PatternMatcher;
192import android.os.Process;
193import android.os.RemoteCallbackList;
194import android.os.RemoteException;
195import android.os.ResultReceiver;
196import android.os.SELinux;
197import android.os.ServiceManager;
198import android.os.ShellCallback;
199import android.os.SystemClock;
200import android.os.SystemProperties;
201import android.os.Trace;
202import android.os.UserHandle;
203import android.os.UserManager;
204import android.os.UserManagerInternal;
205import android.os.storage.IStorageManager;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.StorageManagerInternal;
209import android.os.storage.VolumeInfo;
210import android.os.storage.VolumeRecord;
211import android.provider.Settings.Global;
212import android.provider.Settings.Secure;
213import android.security.KeyStore;
214import android.security.SystemKeyStore;
215import android.service.pm.PackageServiceDumpProto;
216import android.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.BootTimingsTraceLog;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.DumpUtils;
258import com.android.internal.util.FastPrintWriter;
259import com.android.internal.util.FastXmlSerializer;
260import com.android.internal.util.IndentingPrintWriter;
261import com.android.internal.util.Preconditions;
262import com.android.internal.util.XmlUtils;
263import com.android.server.AttributeCache;
264import com.android.server.DeviceIdleController;
265import com.android.server.EventLogTags;
266import com.android.server.FgThread;
267import com.android.server.IntentResolver;
268import com.android.server.LocalServices;
269import com.android.server.LockGuard;
270import com.android.server.ServiceThread;
271import com.android.server.SystemConfig;
272import com.android.server.SystemServerInitThreadPool;
273import com.android.server.Watchdog;
274import com.android.server.net.NetworkPolicyManagerInternal;
275import com.android.server.pm.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
300import java.io.FileOutputStream;
301import java.io.FileReader;
302import java.io.FilenameFilter;
303import java.io.IOException;
304import java.io.PrintWriter;
305import java.lang.annotation.Retention;
306import java.lang.annotation.RetentionPolicy;
307import java.nio.charset.StandardCharsets;
308import java.security.DigestInputStream;
309import java.security.MessageDigest;
310import java.security.NoSuchAlgorithmException;
311import java.security.PublicKey;
312import java.security.SecureRandom;
313import java.security.cert.Certificate;
314import java.security.cert.CertificateEncodingException;
315import java.security.cert.CertificateException;
316import java.text.SimpleDateFormat;
317import java.util.ArrayList;
318import java.util.Arrays;
319import java.util.Collection;
320import java.util.Collections;
321import java.util.Comparator;
322import java.util.Date;
323import java.util.HashMap;
324import java.util.HashSet;
325import java.util.Iterator;
326import java.util.List;
327import java.util.Map;
328import java.util.Objects;
329import java.util.Set;
330import java.util.concurrent.CountDownLatch;
331import java.util.concurrent.Future;
332import java.util.concurrent.TimeUnit;
333import java.util.concurrent.atomic.AtomicBoolean;
334import java.util.concurrent.atomic.AtomicInteger;
335
336/**
337 * Keep track of all those APKs everywhere.
338 * <p>
339 * Internally there are two important locks:
340 * <ul>
341 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
342 * and other related state. It is a fine-grained lock that should only be held
343 * momentarily, as it's one of the most contended locks in the system.
344 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
345 * operations typically involve heavy lifting of application data on disk. Since
346 * {@code installd} is single-threaded, and it's operations can often be slow,
347 * this lock should never be acquired while already holding {@link #mPackages}.
348 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
349 * holding {@link #mInstallLock}.
350 * </ul>
351 * Many internal methods rely on the caller to hold the appropriate locks, and
352 * this contract is expressed through method name suffixes:
353 * <ul>
354 * <li>fooLI(): the caller must hold {@link #mInstallLock}
355 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
356 * being modified must be frozen
357 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
358 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
359 * </ul>
360 * <p>
361 * Because this class is very central to the platform's security; please run all
362 * CTS and unit tests whenever making modifications:
363 *
364 * <pre>
365 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
366 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
367 * </pre>
368 */
369public class PackageManagerService extends IPackageManager.Stub
370        implements PackageSender {
371    static final String TAG = "PackageManager";
372    static final boolean DEBUG_SETTINGS = false;
373    static final boolean DEBUG_PREFERRED = false;
374    static final boolean DEBUG_UPGRADE = false;
375    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
376    private static final boolean DEBUG_BACKUP = false;
377    private static final boolean DEBUG_INSTALL = false;
378    private static final boolean DEBUG_REMOVE = false;
379    private static final boolean DEBUG_BROADCASTS = false;
380    private static final boolean DEBUG_SHOW_INFO = false;
381    private static final boolean DEBUG_PACKAGE_INFO = false;
382    private static final boolean DEBUG_INTENT_MATCHING = false;
383    private static final boolean DEBUG_PACKAGE_SCANNING = false;
384    private static final boolean DEBUG_VERIFY = false;
385    private static final boolean DEBUG_FILTERS = false;
386    private static final boolean DEBUG_PERMISSIONS = false;
387    private static final boolean DEBUG_SHARED_LIBRARIES = false;
388
389    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
390    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
391    // user, but by default initialize to this.
392    public static final boolean DEBUG_DEXOPT = false;
393
394    private static final boolean DEBUG_ABI_SELECTION = false;
395    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
396    private static final boolean DEBUG_TRIAGED_MISSING = false;
397    private static final boolean DEBUG_APP_DATA = false;
398
399    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
400    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
401
402    private static final boolean HIDE_EPHEMERAL_APIS = false;
403
404    private static final boolean ENABLE_FREE_CACHE_V2 =
405            SystemProperties.getBoolean("fw.free_cache_v2", true);
406
407    private static final int RADIO_UID = Process.PHONE_UID;
408    private static final int LOG_UID = Process.LOG_UID;
409    private static final int NFC_UID = Process.NFC_UID;
410    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
411    private static final int SHELL_UID = Process.SHELL_UID;
412
413    // Cap the size of permission trees that 3rd party apps can define
414    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
415
416    // Suffix used during package installation when copying/moving
417    // package apks to install directory.
418    private static final String INSTALL_PACKAGE_SUFFIX = "-";
419
420    static final int SCAN_NO_DEX = 1<<1;
421    static final int SCAN_FORCE_DEX = 1<<2;
422    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
423    static final int SCAN_NEW_INSTALL = 1<<4;
424    static final int SCAN_UPDATE_TIME = 1<<5;
425    static final int SCAN_BOOTING = 1<<6;
426    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
427    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
428    static final int SCAN_REPLACING = 1<<9;
429    static final int SCAN_REQUIRE_KNOWN = 1<<10;
430    static final int SCAN_MOVE = 1<<11;
431    static final int SCAN_INITIAL = 1<<12;
432    static final int SCAN_CHECK_ONLY = 1<<13;
433    static final int SCAN_DONT_KILL_APP = 1<<14;
434    static final int SCAN_IGNORE_FROZEN = 1<<15;
435    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
436    static final int SCAN_AS_INSTANT_APP = 1<<17;
437    static final int SCAN_AS_FULL_APP = 1<<18;
438    /** Should not be with the scan flags */
439    static final int FLAGS_REMOVE_CHATTY = 1<<31;
440
441    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
442
443    private static final int[] EMPTY_INT_ARRAY = new int[0];
444
445    private static final int TYPE_UNKNOWN = 0;
446    private static final int TYPE_ACTIVITY = 1;
447    private static final int TYPE_RECEIVER = 2;
448    private static final int TYPE_SERVICE = 3;
449    private static final int TYPE_PROVIDER = 4;
450    @IntDef(prefix = { "TYPE_" }, value = {
451            TYPE_UNKNOWN,
452            TYPE_ACTIVITY,
453            TYPE_RECEIVER,
454            TYPE_SERVICE,
455            TYPE_PROVIDER,
456    })
457    @Retention(RetentionPolicy.SOURCE)
458    public @interface ComponentType {}
459
460    /**
461     * Timeout (in milliseconds) after which the watchdog should declare that
462     * our handler thread is wedged.  The usual default for such things is one
463     * minute but we sometimes do very lengthy I/O operations on this thread,
464     * such as installing multi-gigabyte applications, so ours needs to be longer.
465     */
466    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
467
468    /**
469     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
470     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
471     * settings entry if available, otherwise we use the hardcoded default.  If it's been
472     * more than this long since the last fstrim, we force one during the boot sequence.
473     *
474     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
475     * one gets run at the next available charging+idle time.  This final mandatory
476     * no-fstrim check kicks in only of the other scheduling criteria is never met.
477     */
478    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
479
480    /**
481     * Whether verification is enabled by default.
482     */
483    private static final boolean DEFAULT_VERIFY_ENABLE = true;
484
485    /**
486     * The default maximum time to wait for the verification agent to return in
487     * milliseconds.
488     */
489    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
490
491    /**
492     * The default response for package verification timeout.
493     *
494     * This can be either PackageManager.VERIFICATION_ALLOW or
495     * PackageManager.VERIFICATION_REJECT.
496     */
497    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
498
499    static final String PLATFORM_PACKAGE_NAME = "android";
500
501    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
502
503    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
504            DEFAULT_CONTAINER_PACKAGE,
505            "com.android.defcontainer.DefaultContainerService");
506
507    private static final String KILL_APP_REASON_GIDS_CHANGED =
508            "permission grant or revoke changed gids";
509
510    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
511            "permissions revoked";
512
513    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
514
515    private static final String PACKAGE_SCHEME = "package";
516
517    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
518
519    /** Permission grant: not grant the permission. */
520    private static final int GRANT_DENIED = 1;
521
522    /** Permission grant: grant the permission as an install permission. */
523    private static final int GRANT_INSTALL = 2;
524
525    /** Permission grant: grant the permission as a runtime one. */
526    private static final int GRANT_RUNTIME = 3;
527
528    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
529    private static final int GRANT_UPGRADE = 4;
530
531    /** Canonical intent used to identify what counts as a "web browser" app */
532    private static final Intent sBrowserIntent;
533    static {
534        sBrowserIntent = new Intent();
535        sBrowserIntent.setAction(Intent.ACTION_VIEW);
536        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
537        sBrowserIntent.setData(Uri.parse("http:"));
538    }
539
540    /**
541     * The set of all protected actions [i.e. those actions for which a high priority
542     * intent filter is disallowed].
543     */
544    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
545    static {
546        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
547        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
548        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
549        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
550    }
551
552    // Compilation reasons.
553    public static final int REASON_FIRST_BOOT = 0;
554    public static final int REASON_BOOT = 1;
555    public static final int REASON_INSTALL = 2;
556    public static final int REASON_BACKGROUND_DEXOPT = 3;
557    public static final int REASON_AB_OTA = 4;
558
559    public static final int REASON_LAST = REASON_AB_OTA;
560
561    /** All dangerous permission names in the same order as the events in MetricsEvent */
562    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
563            Manifest.permission.READ_CALENDAR,
564            Manifest.permission.WRITE_CALENDAR,
565            Manifest.permission.CAMERA,
566            Manifest.permission.READ_CONTACTS,
567            Manifest.permission.WRITE_CONTACTS,
568            Manifest.permission.GET_ACCOUNTS,
569            Manifest.permission.ACCESS_FINE_LOCATION,
570            Manifest.permission.ACCESS_COARSE_LOCATION,
571            Manifest.permission.RECORD_AUDIO,
572            Manifest.permission.READ_PHONE_STATE,
573            Manifest.permission.CALL_PHONE,
574            Manifest.permission.READ_CALL_LOG,
575            Manifest.permission.WRITE_CALL_LOG,
576            Manifest.permission.ADD_VOICEMAIL,
577            Manifest.permission.USE_SIP,
578            Manifest.permission.PROCESS_OUTGOING_CALLS,
579            Manifest.permission.READ_CELL_BROADCASTS,
580            Manifest.permission.BODY_SENSORS,
581            Manifest.permission.SEND_SMS,
582            Manifest.permission.RECEIVE_SMS,
583            Manifest.permission.READ_SMS,
584            Manifest.permission.RECEIVE_WAP_PUSH,
585            Manifest.permission.RECEIVE_MMS,
586            Manifest.permission.READ_EXTERNAL_STORAGE,
587            Manifest.permission.WRITE_EXTERNAL_STORAGE,
588            Manifest.permission.READ_PHONE_NUMBERS,
589            Manifest.permission.ANSWER_PHONE_CALLS);
590
591
592    /**
593     * Version number for the package parser cache. Increment this whenever the format or
594     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
595     */
596    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
597
598    /**
599     * Whether the package parser cache is enabled.
600     */
601    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
602
603    final ServiceThread mHandlerThread;
604
605    final PackageHandler mHandler;
606
607    private final ProcessLoggingHandler mProcessLoggingHandler;
608
609    /**
610     * Messages for {@link #mHandler} that need to wait for system ready before
611     * being dispatched.
612     */
613    private ArrayList<Message> mPostSystemReadyMessages;
614
615    final int mSdkVersion = Build.VERSION.SDK_INT;
616
617    final Context mContext;
618    final boolean mFactoryTest;
619    final boolean mOnlyCore;
620    final DisplayMetrics mMetrics;
621    final int mDefParseFlags;
622    final String[] mSeparateProcesses;
623    final boolean mIsUpgrade;
624    final boolean mIsPreNUpgrade;
625    final boolean mIsPreNMR1Upgrade;
626
627    // Have we told the Activity Manager to whitelist the default container service by uid yet?
628    @GuardedBy("mPackages")
629    boolean mDefaultContainerWhitelisted = false;
630
631    @GuardedBy("mPackages")
632    private boolean mDexOptDialogShown;
633
634    /** The location for ASEC container files on internal storage. */
635    final String mAsecInternalPath;
636
637    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
638    // LOCK HELD.  Can be called with mInstallLock held.
639    @GuardedBy("mInstallLock")
640    final Installer mInstaller;
641
642    /** Directory where installed third-party apps stored */
643    final File mAppInstallDir;
644
645    /**
646     * Directory to which applications installed internally have their
647     * 32 bit native libraries copied.
648     */
649    private File mAppLib32InstallDir;
650
651    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
652    // apps.
653    final File mDrmAppPrivateInstallDir;
654
655    // ----------------------------------------------------------------
656
657    // Lock for state used when installing and doing other long running
658    // operations.  Methods that must be called with this lock held have
659    // the suffix "LI".
660    final Object mInstallLock = new Object();
661
662    // ----------------------------------------------------------------
663
664    // Keys are String (package name), values are Package.  This also serves
665    // as the lock for the global state.  Methods that must be called with
666    // this lock held have the prefix "LP".
667    @GuardedBy("mPackages")
668    final ArrayMap<String, PackageParser.Package> mPackages =
669            new ArrayMap<String, PackageParser.Package>();
670
671    final ArrayMap<String, Set<String>> mKnownCodebase =
672            new ArrayMap<String, Set<String>>();
673
674    // Keys are isolated uids and values are the uid of the application
675    // that created the isolated proccess.
676    @GuardedBy("mPackages")
677    final SparseIntArray mIsolatedOwners = new SparseIntArray();
678
679    // List of APK paths to load for each user and package. This data is never
680    // persisted by the package manager. Instead, the overlay manager will
681    // ensure the data is up-to-date in runtime.
682    @GuardedBy("mPackages")
683    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
684        new SparseArray<ArrayMap<String, ArrayList<String>>>();
685
686    /**
687     * Tracks new system packages [received in an OTA] that we expect to
688     * find updated user-installed versions. Keys are package name, values
689     * are package location.
690     */
691    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
692    /**
693     * Tracks high priority intent filters for protected actions. During boot, certain
694     * filter actions are protected and should never be allowed to have a high priority
695     * intent filter for them. However, there is one, and only one exception -- the
696     * setup wizard. It must be able to define a high priority intent filter for these
697     * actions to ensure there are no escapes from the wizard. We need to delay processing
698     * of these during boot as we need to look at all of the system packages in order
699     * to know which component is the setup wizard.
700     */
701    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
702    /**
703     * Whether or not processing protected filters should be deferred.
704     */
705    private boolean mDeferProtectedFilters = true;
706
707    /**
708     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
709     */
710    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
711    /**
712     * Whether or not system app permissions should be promoted from install to runtime.
713     */
714    boolean mPromoteSystemApps;
715
716    @GuardedBy("mPackages")
717    final Settings mSettings;
718
719    /**
720     * Set of package names that are currently "frozen", which means active
721     * surgery is being done on the code/data for that package. The platform
722     * will refuse to launch frozen packages to avoid race conditions.
723     *
724     * @see PackageFreezer
725     */
726    @GuardedBy("mPackages")
727    final ArraySet<String> mFrozenPackages = new ArraySet<>();
728
729    final ProtectedPackages mProtectedPackages;
730
731    boolean mFirstBoot;
732
733    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
734
735    // System configuration read by SystemConfig.
736    final int[] mGlobalGids;
737    final SparseArray<ArraySet<String>> mSystemPermissions;
738    @GuardedBy("mAvailableFeatures")
739    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
740
741    // If mac_permissions.xml was found for seinfo labeling.
742    boolean mFoundPolicyFile;
743
744    private final InstantAppRegistry mInstantAppRegistry;
745
746    @GuardedBy("mPackages")
747    int mChangedPackagesSequenceNumber;
748    /**
749     * List of changed [installed, removed or updated] packages.
750     * mapping from user id -> sequence number -> package name
751     */
752    @GuardedBy("mPackages")
753    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
754    /**
755     * The sequence number of the last change to a package.
756     * mapping from user id -> package name -> sequence number
757     */
758    @GuardedBy("mPackages")
759    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
760
761    class PackageParserCallback implements PackageParser.Callback {
762        @Override public final boolean hasFeature(String feature) {
763            return PackageManagerService.this.hasSystemFeature(feature, 0);
764        }
765
766        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
767                Collection<PackageParser.Package> allPackages, String targetPackageName) {
768            List<PackageParser.Package> overlayPackages = null;
769            for (PackageParser.Package p : allPackages) {
770                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
771                    if (overlayPackages == null) {
772                        overlayPackages = new ArrayList<PackageParser.Package>();
773                    }
774                    overlayPackages.add(p);
775                }
776            }
777            if (overlayPackages != null) {
778                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
779                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
780                        return p1.mOverlayPriority - p2.mOverlayPriority;
781                    }
782                };
783                Collections.sort(overlayPackages, cmp);
784            }
785            return overlayPackages;
786        }
787
788        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
789                String targetPackageName, String targetPath) {
790            if ("android".equals(targetPackageName)) {
791                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
792                // native AssetManager.
793                return null;
794            }
795            List<PackageParser.Package> overlayPackages =
796                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
797            if (overlayPackages == null || overlayPackages.isEmpty()) {
798                return null;
799            }
800            List<String> overlayPathList = null;
801            for (PackageParser.Package overlayPackage : overlayPackages) {
802                if (targetPath == null) {
803                    if (overlayPathList == null) {
804                        overlayPathList = new ArrayList<String>();
805                    }
806                    overlayPathList.add(overlayPackage.baseCodePath);
807                    continue;
808                }
809
810                try {
811                    // Creates idmaps for system to parse correctly the Android manifest of the
812                    // target package.
813                    //
814                    // OverlayManagerService will update each of them with a correct gid from its
815                    // target package app id.
816                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
817                            UserHandle.getSharedAppGid(
818                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                } catch (InstallerException e) {
824                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
825                            overlayPackage.baseCodePath);
826                }
827            }
828            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
829        }
830
831        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
832            synchronized (mPackages) {
833                return getStaticOverlayPathsLocked(
834                        mPackages.values(), targetPackageName, targetPath);
835            }
836        }
837
838        @Override public final String[] getOverlayApks(String targetPackageName) {
839            return getStaticOverlayPaths(targetPackageName, null);
840        }
841
842        @Override public final String[] getOverlayPaths(String targetPackageName,
843                String targetPath) {
844            return getStaticOverlayPaths(targetPackageName, targetPath);
845        }
846    };
847
848    class ParallelPackageParserCallback extends PackageParserCallback {
849        List<PackageParser.Package> mOverlayPackages = null;
850
851        void findStaticOverlayPackages() {
852            synchronized (mPackages) {
853                for (PackageParser.Package p : mPackages.values()) {
854                    if (p.mIsStaticOverlay) {
855                        if (mOverlayPackages == null) {
856                            mOverlayPackages = new ArrayList<PackageParser.Package>();
857                        }
858                        mOverlayPackages.add(p);
859                    }
860                }
861            }
862        }
863
864        @Override
865        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
866            // We can trust mOverlayPackages without holding mPackages because package uninstall
867            // can't happen while running parallel parsing.
868            // Moreover holding mPackages on each parsing thread causes dead-lock.
869            return mOverlayPackages == null ? null :
870                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
871        }
872    }
873
874    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
875    final ParallelPackageParserCallback mParallelPackageParserCallback =
876            new ParallelPackageParserCallback();
877
878    public static final class SharedLibraryEntry {
879        public final @Nullable String path;
880        public final @Nullable String apk;
881        public final @NonNull SharedLibraryInfo info;
882
883        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
884                String declaringPackageName, int declaringPackageVersionCode) {
885            path = _path;
886            apk = _apk;
887            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
888                    declaringPackageName, declaringPackageVersionCode), null);
889        }
890    }
891
892    // Currently known shared libraries.
893    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
894    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
895            new ArrayMap<>();
896
897    // All available activities, for your resolving pleasure.
898    final ActivityIntentResolver mActivities =
899            new ActivityIntentResolver();
900
901    // All available receivers, for your resolving pleasure.
902    final ActivityIntentResolver mReceivers =
903            new ActivityIntentResolver();
904
905    // All available services, for your resolving pleasure.
906    final ServiceIntentResolver mServices = new ServiceIntentResolver();
907
908    // All available providers, for your resolving pleasure.
909    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
910
911    // Mapping from provider base names (first directory in content URI codePath)
912    // to the provider information.
913    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
914            new ArrayMap<String, PackageParser.Provider>();
915
916    // Mapping from instrumentation class names to info about them.
917    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
918            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
919
920    // Mapping from permission names to info about them.
921    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
922            new ArrayMap<String, PackageParser.PermissionGroup>();
923
924    // Packages whose data we have transfered into another package, thus
925    // should no longer exist.
926    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
927
928    // Broadcast actions that are only available to the system.
929    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
930
931    /** List of packages waiting for verification. */
932    final SparseArray<PackageVerificationState> mPendingVerification
933            = new SparseArray<PackageVerificationState>();
934
935    /** Set of packages associated with each app op permission. */
936    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
937
938    final PackageInstallerService mInstallerService;
939
940    private final PackageDexOptimizer mPackageDexOptimizer;
941    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
942    // is used by other apps).
943    private final DexManager mDexManager;
944
945    private AtomicInteger mNextMoveId = new AtomicInteger();
946    private final MoveCallbacks mMoveCallbacks;
947
948    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
949
950    // Cache of users who need badging.
951    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
952
953    /** Token for keys in mPendingVerification. */
954    private int mPendingVerificationToken = 0;
955
956    volatile boolean mSystemReady;
957    volatile boolean mSafeMode;
958    volatile boolean mHasSystemUidErrors;
959    private volatile boolean mEphemeralAppsDisabled;
960
961    ApplicationInfo mAndroidApplication;
962    final ActivityInfo mResolveActivity = new ActivityInfo();
963    final ResolveInfo mResolveInfo = new ResolveInfo();
964    ComponentName mResolveComponentName;
965    PackageParser.Package mPlatformPackage;
966    ComponentName mCustomResolverComponentName;
967
968    boolean mResolverReplaced = false;
969
970    private final @Nullable ComponentName mIntentFilterVerifierComponent;
971    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
972
973    private int mIntentFilterVerificationToken = 0;
974
975    /** The service connection to the ephemeral resolver */
976    final EphemeralResolverConnection mInstantAppResolverConnection;
977    /** Component used to show resolver settings for Instant Apps */
978    final ComponentName mInstantAppResolverSettingsComponent;
979
980    /** Activity used to install instant applications */
981    ActivityInfo mInstantAppInstallerActivity;
982    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
983
984    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
985            = new SparseArray<IntentFilterVerificationState>();
986
987    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
988
989    // List of packages names to keep cached, even if they are uninstalled for all users
990    private List<String> mKeepUninstalledPackages;
991
992    private UserManagerInternal mUserManagerInternal;
993
994    private DeviceIdleController.LocalService mDeviceIdleController;
995
996    private File mCacheDir;
997
998    private ArraySet<String> mPrivappPermissionsViolations;
999
1000    private Future<?> mPrepareAppDataFuture;
1001
1002    private static class IFVerificationParams {
1003        PackageParser.Package pkg;
1004        boolean replacing;
1005        int userId;
1006        int verifierUid;
1007
1008        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1009                int _userId, int _verifierUid) {
1010            pkg = _pkg;
1011            replacing = _replacing;
1012            userId = _userId;
1013            replacing = _replacing;
1014            verifierUid = _verifierUid;
1015        }
1016    }
1017
1018    private interface IntentFilterVerifier<T extends IntentFilter> {
1019        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1020                                               T filter, String packageName);
1021        void startVerifications(int userId);
1022        void receiveVerificationResponse(int verificationId);
1023    }
1024
1025    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1026        private Context mContext;
1027        private ComponentName mIntentFilterVerifierComponent;
1028        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1029
1030        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1031            mContext = context;
1032            mIntentFilterVerifierComponent = verifierComponent;
1033        }
1034
1035        private String getDefaultScheme() {
1036            return IntentFilter.SCHEME_HTTPS;
1037        }
1038
1039        @Override
1040        public void startVerifications(int userId) {
1041            // Launch verifications requests
1042            int count = mCurrentIntentFilterVerifications.size();
1043            for (int n=0; n<count; n++) {
1044                int verificationId = mCurrentIntentFilterVerifications.get(n);
1045                final IntentFilterVerificationState ivs =
1046                        mIntentFilterVerificationStates.get(verificationId);
1047
1048                String packageName = ivs.getPackageName();
1049
1050                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1051                final int filterCount = filters.size();
1052                ArraySet<String> domainsSet = new ArraySet<>();
1053                for (int m=0; m<filterCount; m++) {
1054                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1055                    domainsSet.addAll(filter.getHostsList());
1056                }
1057                synchronized (mPackages) {
1058                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1059                            packageName, domainsSet) != null) {
1060                        scheduleWriteSettingsLocked();
1061                    }
1062                }
1063                sendVerificationRequest(userId, verificationId, ivs);
1064            }
1065            mCurrentIntentFilterVerifications.clear();
1066        }
1067
1068        private void sendVerificationRequest(int userId, int verificationId,
1069                IntentFilterVerificationState ivs) {
1070
1071            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1072            verificationIntent.putExtra(
1073                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1074                    verificationId);
1075            verificationIntent.putExtra(
1076                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1077                    getDefaultScheme());
1078            verificationIntent.putExtra(
1079                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1080                    ivs.getHostsString());
1081            verificationIntent.putExtra(
1082                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1083                    ivs.getPackageName());
1084            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1085            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1086
1087            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1088            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1089                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1090                    userId, false, "intent filter verifier");
1091
1092            UserHandle user = new UserHandle(userId);
1093            mContext.sendBroadcastAsUser(verificationIntent, user);
1094            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1095                    "Sending IntentFilter verification broadcast");
1096        }
1097
1098        public void receiveVerificationResponse(int verificationId) {
1099            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1100
1101            final boolean verified = ivs.isVerified();
1102
1103            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1104            final int count = filters.size();
1105            if (DEBUG_DOMAIN_VERIFICATION) {
1106                Slog.i(TAG, "Received verification response " + verificationId
1107                        + " for " + count + " filters, verified=" + verified);
1108            }
1109            for (int n=0; n<count; n++) {
1110                PackageParser.ActivityIntentInfo filter = filters.get(n);
1111                filter.setVerified(verified);
1112
1113                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1114                        + " verified with result:" + verified + " and hosts:"
1115                        + ivs.getHostsString());
1116            }
1117
1118            mIntentFilterVerificationStates.remove(verificationId);
1119
1120            final String packageName = ivs.getPackageName();
1121            IntentFilterVerificationInfo ivi = null;
1122
1123            synchronized (mPackages) {
1124                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1125            }
1126            if (ivi == null) {
1127                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1128                        + verificationId + " packageName:" + packageName);
1129                return;
1130            }
1131            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1132                    "Updating IntentFilterVerificationInfo for package " + packageName
1133                            +" verificationId:" + verificationId);
1134
1135            synchronized (mPackages) {
1136                if (verified) {
1137                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1138                } else {
1139                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1140                }
1141                scheduleWriteSettingsLocked();
1142
1143                final int userId = ivs.getUserId();
1144                if (userId != UserHandle.USER_ALL) {
1145                    final int userStatus =
1146                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1147
1148                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1149                    boolean needUpdate = false;
1150
1151                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1152                    // already been set by the User thru the Disambiguation dialog
1153                    switch (userStatus) {
1154                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1155                            if (verified) {
1156                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1157                            } else {
1158                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1159                            }
1160                            needUpdate = true;
1161                            break;
1162
1163                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1164                            if (verified) {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1166                                needUpdate = true;
1167                            }
1168                            break;
1169
1170                        default:
1171                            // Nothing to do
1172                    }
1173
1174                    if (needUpdate) {
1175                        mSettings.updateIntentFilterVerificationStatusLPw(
1176                                packageName, updatedStatus, userId);
1177                        scheduleWritePackageRestrictionsLocked(userId);
1178                    }
1179                }
1180            }
1181        }
1182
1183        @Override
1184        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1185                    ActivityIntentInfo filter, String packageName) {
1186            if (!hasValidDomains(filter)) {
1187                return false;
1188            }
1189            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1190            if (ivs == null) {
1191                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1192                        packageName);
1193            }
1194            if (DEBUG_DOMAIN_VERIFICATION) {
1195                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1196            }
1197            ivs.addFilter(filter);
1198            return true;
1199        }
1200
1201        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1202                int userId, int verificationId, String packageName) {
1203            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1204                    verifierUid, userId, packageName);
1205            ivs.setPendingState();
1206            synchronized (mPackages) {
1207                mIntentFilterVerificationStates.append(verificationId, ivs);
1208                mCurrentIntentFilterVerifications.add(verificationId);
1209            }
1210            return ivs;
1211        }
1212    }
1213
1214    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1215        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1216                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1217                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1218    }
1219
1220    // Set of pending broadcasts for aggregating enable/disable of components.
1221    static class PendingPackageBroadcasts {
1222        // for each user id, a map of <package name -> components within that package>
1223        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1224
1225        public PendingPackageBroadcasts() {
1226            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1227        }
1228
1229        public ArrayList<String> get(int userId, String packageName) {
1230            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231            return packages.get(packageName);
1232        }
1233
1234        public void put(int userId, String packageName, ArrayList<String> components) {
1235            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1236            packages.put(packageName, components);
1237        }
1238
1239        public void remove(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1241            if (packages != null) {
1242                packages.remove(packageName);
1243            }
1244        }
1245
1246        public void remove(int userId) {
1247            mUidMap.remove(userId);
1248        }
1249
1250        public int userIdCount() {
1251            return mUidMap.size();
1252        }
1253
1254        public int userIdAt(int n) {
1255            return mUidMap.keyAt(n);
1256        }
1257
1258        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1259            return mUidMap.get(userId);
1260        }
1261
1262        public int size() {
1263            // total number of pending broadcast entries across all userIds
1264            int num = 0;
1265            for (int i = 0; i< mUidMap.size(); i++) {
1266                num += mUidMap.valueAt(i).size();
1267            }
1268            return num;
1269        }
1270
1271        public void clear() {
1272            mUidMap.clear();
1273        }
1274
1275        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1276            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1277            if (map == null) {
1278                map = new ArrayMap<String, ArrayList<String>>();
1279                mUidMap.put(userId, map);
1280            }
1281            return map;
1282        }
1283    }
1284    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1285
1286    // Service Connection to remote media container service to copy
1287    // package uri's from external media onto secure containers
1288    // or internal storage.
1289    private IMediaContainerService mContainerService = null;
1290
1291    static final int SEND_PENDING_BROADCAST = 1;
1292    static final int MCS_BOUND = 3;
1293    static final int END_COPY = 4;
1294    static final int INIT_COPY = 5;
1295    static final int MCS_UNBIND = 6;
1296    static final int START_CLEANING_PACKAGE = 7;
1297    static final int FIND_INSTALL_LOC = 8;
1298    static final int POST_INSTALL = 9;
1299    static final int MCS_RECONNECT = 10;
1300    static final int MCS_GIVE_UP = 11;
1301    static final int UPDATED_MEDIA_STATUS = 12;
1302    static final int WRITE_SETTINGS = 13;
1303    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1304    static final int PACKAGE_VERIFIED = 15;
1305    static final int CHECK_PENDING_VERIFICATION = 16;
1306    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1307    static final int INTENT_FILTER_VERIFIED = 18;
1308    static final int WRITE_PACKAGE_LIST = 19;
1309    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1310
1311    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1312
1313    // Delay time in millisecs
1314    static final int BROADCAST_DELAY = 10 * 1000;
1315
1316    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1317            2 * 60 * 60 * 1000L; /* two hours */
1318
1319    static UserManagerService sUserManager;
1320
1321    // Stores a list of users whose package restrictions file needs to be updated
1322    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1323
1324    final private DefaultContainerConnection mDefContainerConn =
1325            new DefaultContainerConnection();
1326    class DefaultContainerConnection implements ServiceConnection {
1327        public void onServiceConnected(ComponentName name, IBinder service) {
1328            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1329            final IMediaContainerService imcs = IMediaContainerService.Stub
1330                    .asInterface(Binder.allowBlocking(service));
1331            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1332        }
1333
1334        public void onServiceDisconnected(ComponentName name) {
1335            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1336        }
1337    }
1338
1339    // Recordkeeping of restore-after-install operations that are currently in flight
1340    // between the Package Manager and the Backup Manager
1341    static class PostInstallData {
1342        public InstallArgs args;
1343        public PackageInstalledInfo res;
1344
1345        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1346            args = _a;
1347            res = _r;
1348        }
1349    }
1350
1351    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1352    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1353
1354    // XML tags for backup/restore of various bits of state
1355    private static final String TAG_PREFERRED_BACKUP = "pa";
1356    private static final String TAG_DEFAULT_APPS = "da";
1357    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1358
1359    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1360    private static final String TAG_ALL_GRANTS = "rt-grants";
1361    private static final String TAG_GRANT = "grant";
1362    private static final String ATTR_PACKAGE_NAME = "pkg";
1363
1364    private static final String TAG_PERMISSION = "perm";
1365    private static final String ATTR_PERMISSION_NAME = "name";
1366    private static final String ATTR_IS_GRANTED = "g";
1367    private static final String ATTR_USER_SET = "set";
1368    private static final String ATTR_USER_FIXED = "fixed";
1369    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1370
1371    // System/policy permission grants are not backed up
1372    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1373            FLAG_PERMISSION_POLICY_FIXED
1374            | FLAG_PERMISSION_SYSTEM_FIXED
1375            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1376
1377    // And we back up these user-adjusted states
1378    private static final int USER_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_USER_SET
1380            | FLAG_PERMISSION_USER_FIXED
1381            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1382
1383    final @Nullable String mRequiredVerifierPackage;
1384    final @NonNull String mRequiredInstallerPackage;
1385    final @NonNull String mRequiredUninstallerPackage;
1386    final @Nullable String mSetupWizardPackage;
1387    final @Nullable String mStorageManagerPackage;
1388    final @NonNull String mServicesSystemSharedLibraryPackageName;
1389    final @NonNull String mSharedSystemSharedLibraryPackageName;
1390
1391    final boolean mPermissionReviewRequired;
1392
1393    private final PackageUsage mPackageUsage = new PackageUsage();
1394    private final CompilerStats mCompilerStats = new CompilerStats();
1395
1396    class PackageHandler extends Handler {
1397        private boolean mBound = false;
1398        final ArrayList<HandlerParams> mPendingInstalls =
1399            new ArrayList<HandlerParams>();
1400
1401        private boolean connectToService() {
1402            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1403                    " DefaultContainerService");
1404            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1405            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1407                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1408                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409                mBound = true;
1410                return true;
1411            }
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413            return false;
1414        }
1415
1416        private void disconnectService() {
1417            mContainerService = null;
1418            mBound = false;
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            mContext.unbindService(mDefContainerConn);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422        }
1423
1424        PackageHandler(Looper looper) {
1425            super(looper);
1426        }
1427
1428        public void handleMessage(Message msg) {
1429            try {
1430                doHandleMessage(msg);
1431            } finally {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            }
1434        }
1435
1436        void doHandleMessage(Message msg) {
1437            switch (msg.what) {
1438                case INIT_COPY: {
1439                    HandlerParams params = (HandlerParams) msg.obj;
1440                    int idx = mPendingInstalls.size();
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1442                    // If a bind was already initiated we dont really
1443                    // need to do anything. The pending install
1444                    // will be processed later on.
1445                    if (!mBound) {
1446                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1447                                System.identityHashCode(mHandler));
1448                        // If this is the only one pending we might
1449                        // have to bind to the service again.
1450                        if (!connectToService()) {
1451                            Slog.e(TAG, "Failed to bind to media container service");
1452                            params.serviceError();
1453                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                    System.identityHashCode(mHandler));
1455                            if (params.traceMethod != null) {
1456                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1457                                        params.traceCookie);
1458                            }
1459                            return;
1460                        } else {
1461                            // Once we bind to the service, the first
1462                            // pending request will be processed.
1463                            mPendingInstalls.add(idx, params);
1464                        }
1465                    } else {
1466                        mPendingInstalls.add(idx, params);
1467                        // Already bound to the service. Just make
1468                        // sure we trigger off processing the first request.
1469                        if (idx == 0) {
1470                            mHandler.sendEmptyMessage(MCS_BOUND);
1471                        }
1472                    }
1473                    break;
1474                }
1475                case MCS_BOUND: {
1476                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1477                    if (msg.obj != null) {
1478                        mContainerService = (IMediaContainerService) msg.obj;
1479                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1480                                System.identityHashCode(mHandler));
1481                    }
1482                    if (mContainerService == null) {
1483                        if (!mBound) {
1484                            // Something seriously wrong since we are not bound and we are not
1485                            // waiting for connection. Bail out.
1486                            Slog.e(TAG, "Cannot bind to media container service");
1487                            for (HandlerParams params : mPendingInstalls) {
1488                                // Indicate service bind error
1489                                params.serviceError();
1490                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1491                                        System.identityHashCode(params));
1492                                if (params.traceMethod != null) {
1493                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1494                                            params.traceMethod, params.traceCookie);
1495                                }
1496                                return;
1497                            }
1498                            mPendingInstalls.clear();
1499                        } else {
1500                            Slog.w(TAG, "Waiting to connect to media container service");
1501                        }
1502                    } else if (mPendingInstalls.size() > 0) {
1503                        HandlerParams params = mPendingInstalls.get(0);
1504                        if (params != null) {
1505                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                                    System.identityHashCode(params));
1507                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1508                            if (params.startCopy()) {
1509                                // We are done...  look for more work or to
1510                                // go idle.
1511                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                        "Checking for more work or unbind...");
1513                                // Delete pending install
1514                                if (mPendingInstalls.size() > 0) {
1515                                    mPendingInstalls.remove(0);
1516                                }
1517                                if (mPendingInstalls.size() == 0) {
1518                                    if (mBound) {
1519                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1520                                                "Posting delayed MCS_UNBIND");
1521                                        removeMessages(MCS_UNBIND);
1522                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1523                                        // Unbind after a little delay, to avoid
1524                                        // continual thrashing.
1525                                        sendMessageDelayed(ubmsg, 10000);
1526                                    }
1527                                } else {
1528                                    // There are more pending requests in queue.
1529                                    // Just post MCS_BOUND message to trigger processing
1530                                    // of next pending install.
1531                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                            "Posting MCS_BOUND for next work");
1533                                    mHandler.sendEmptyMessage(MCS_BOUND);
1534                                }
1535                            }
1536                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1537                        }
1538                    } else {
1539                        // Should never happen ideally.
1540                        Slog.w(TAG, "Empty queue");
1541                    }
1542                    break;
1543                }
1544                case MCS_RECONNECT: {
1545                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1546                    if (mPendingInstalls.size() > 0) {
1547                        if (mBound) {
1548                            disconnectService();
1549                        }
1550                        if (!connectToService()) {
1551                            Slog.e(TAG, "Failed to bind to media container service");
1552                            for (HandlerParams params : mPendingInstalls) {
1553                                // Indicate service bind error
1554                                params.serviceError();
1555                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1556                                        System.identityHashCode(params));
1557                            }
1558                            mPendingInstalls.clear();
1559                        }
1560                    }
1561                    break;
1562                }
1563                case MCS_UNBIND: {
1564                    // If there is no actual work left, then time to unbind.
1565                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1566
1567                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1568                        if (mBound) {
1569                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1570
1571                            disconnectService();
1572                        }
1573                    } else if (mPendingInstalls.size() > 0) {
1574                        // There are more pending requests in queue.
1575                        // Just post MCS_BOUND message to trigger processing
1576                        // of next pending install.
1577                        mHandler.sendEmptyMessage(MCS_BOUND);
1578                    }
1579
1580                    break;
1581                }
1582                case MCS_GIVE_UP: {
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1584                    HandlerParams params = mPendingInstalls.remove(0);
1585                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                            System.identityHashCode(params));
1587                    break;
1588                }
1589                case SEND_PENDING_BROADCAST: {
1590                    String packages[];
1591                    ArrayList<String> components[];
1592                    int size = 0;
1593                    int uids[];
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        if (mPendingBroadcasts == null) {
1597                            return;
1598                        }
1599                        size = mPendingBroadcasts.size();
1600                        if (size <= 0) {
1601                            // Nothing to be done. Just return
1602                            return;
1603                        }
1604                        packages = new String[size];
1605                        components = new ArrayList[size];
1606                        uids = new int[size];
1607                        int i = 0;  // filling out the above arrays
1608
1609                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1610                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1611                            Iterator<Map.Entry<String, ArrayList<String>>> it
1612                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1613                                            .entrySet().iterator();
1614                            while (it.hasNext() && i < size) {
1615                                Map.Entry<String, ArrayList<String>> ent = it.next();
1616                                packages[i] = ent.getKey();
1617                                components[i] = ent.getValue();
1618                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1619                                uids[i] = (ps != null)
1620                                        ? UserHandle.getUid(packageUserId, ps.appId)
1621                                        : -1;
1622                                i++;
1623                            }
1624                        }
1625                        size = i;
1626                        mPendingBroadcasts.clear();
1627                    }
1628                    // Send broadcasts
1629                    for (int i = 0; i < size; i++) {
1630                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1631                    }
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1633                    break;
1634                }
1635                case START_CLEANING_PACKAGE: {
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1637                    final String packageName = (String)msg.obj;
1638                    final int userId = msg.arg1;
1639                    final boolean andCode = msg.arg2 != 0;
1640                    synchronized (mPackages) {
1641                        if (userId == UserHandle.USER_ALL) {
1642                            int[] users = sUserManager.getUserIds();
1643                            for (int user : users) {
1644                                mSettings.addPackageToCleanLPw(
1645                                        new PackageCleanItem(user, packageName, andCode));
1646                            }
1647                        } else {
1648                            mSettings.addPackageToCleanLPw(
1649                                    new PackageCleanItem(userId, packageName, andCode));
1650                        }
1651                    }
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1653                    startCleaningPackages();
1654                } break;
1655                case POST_INSTALL: {
1656                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1657
1658                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1659                    final boolean didRestore = (msg.arg2 != 0);
1660                    mRunningInstalls.delete(msg.arg1);
1661
1662                    if (data != null) {
1663                        InstallArgs args = data.args;
1664                        PackageInstalledInfo parentRes = data.res;
1665
1666                        final boolean grantPermissions = (args.installFlags
1667                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1668                        final boolean killApp = (args.installFlags
1669                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1670                        final String[] grantedPermissions = args.installGrantPermissions;
1671
1672                        // Handle the parent package
1673                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1674                                grantedPermissions, didRestore, args.installerPackageName,
1675                                args.observer);
1676
1677                        // Handle the child packages
1678                        final int childCount = (parentRes.addedChildPackages != null)
1679                                ? parentRes.addedChildPackages.size() : 0;
1680                        for (int i = 0; i < childCount; i++) {
1681                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1682                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1683                                    grantedPermissions, false, args.installerPackageName,
1684                                    args.observer);
1685                        }
1686
1687                        // Log tracing if needed
1688                        if (args.traceMethod != null) {
1689                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1690                                    args.traceCookie);
1691                        }
1692                    } else {
1693                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1694                    }
1695
1696                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1697                } break;
1698                case UPDATED_MEDIA_STATUS: {
1699                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1700                    boolean reportStatus = msg.arg1 == 1;
1701                    boolean doGc = msg.arg2 == 1;
1702                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1703                    if (doGc) {
1704                        // Force a gc to clear up stale containers.
1705                        Runtime.getRuntime().gc();
1706                    }
1707                    if (msg.obj != null) {
1708                        @SuppressWarnings("unchecked")
1709                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1710                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1711                        // Unload containers
1712                        unloadAllContainers(args);
1713                    }
1714                    if (reportStatus) {
1715                        try {
1716                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1717                                    "Invoking StorageManagerService call back");
1718                            PackageHelper.getStorageManager().finishMediaUpdate();
1719                        } catch (RemoteException e) {
1720                            Log.e(TAG, "StorageManagerService not running?");
1721                        }
1722                    }
1723                } break;
1724                case WRITE_SETTINGS: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_SETTINGS);
1728                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1729                        mSettings.writeLPr();
1730                        mDirtyUsers.clear();
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case WRITE_PACKAGE_RESTRICTIONS: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1738                        for (int userId : mDirtyUsers) {
1739                            mSettings.writePackageRestrictionsLPr(userId);
1740                        }
1741                        mDirtyUsers.clear();
1742                    }
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1744                } break;
1745                case WRITE_PACKAGE_LIST: {
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1747                    synchronized (mPackages) {
1748                        removeMessages(WRITE_PACKAGE_LIST);
1749                        mSettings.writePackageListLPr(msg.arg1);
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case CHECK_PENDING_VERIFICATION: {
1754                    final int verificationId = msg.arg1;
1755                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1756
1757                    if ((state != null) && !state.timeoutExtended()) {
1758                        final InstallArgs args = state.getInstallArgs();
1759                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1760
1761                        Slog.i(TAG, "Verification timed out for " + originUri);
1762                        mPendingVerification.remove(verificationId);
1763
1764                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1765
1766                        final UserHandle user = args.getUser();
1767                        if (getDefaultVerificationResponse(user)
1768                                == PackageManager.VERIFICATION_ALLOW) {
1769                            Slog.i(TAG, "Continuing with installation of " + originUri);
1770                            state.setVerifierResponse(Binder.getCallingUid(),
1771                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    PackageManager.VERIFICATION_ALLOW, user);
1774                            try {
1775                                ret = args.copyApk(mContainerService, true);
1776                            } catch (RemoteException e) {
1777                                Slog.e(TAG, "Could not contact the ContainerService");
1778                            }
1779                        } else {
1780                            broadcastPackageVerified(verificationId, originUri,
1781                                    PackageManager.VERIFICATION_REJECT, user);
1782                        }
1783
1784                        Trace.asyncTraceEnd(
1785                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1786
1787                        processPendingInstall(args, ret);
1788                        mHandler.sendEmptyMessage(MCS_UNBIND);
1789                    }
1790                    break;
1791                }
1792                case PACKAGE_VERIFIED: {
1793                    final int verificationId = msg.arg1;
1794
1795                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1796                    if (state == null) {
1797                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1798                        break;
1799                    }
1800
1801                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1802
1803                    state.setVerifierResponse(response.callerUid, response.code);
1804
1805                    if (state.isVerificationComplete()) {
1806                        mPendingVerification.remove(verificationId);
1807
1808                        final InstallArgs args = state.getInstallArgs();
1809                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1810
1811                        int ret;
1812                        if (state.isInstallAllowed()) {
1813                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1814                            broadcastPackageVerified(verificationId, originUri,
1815                                    response.code, state.getInstallArgs().getUser());
1816                            try {
1817                                ret = args.copyApk(mContainerService, true);
1818                            } catch (RemoteException e) {
1819                                Slog.e(TAG, "Could not contact the ContainerService");
1820                            }
1821                        } else {
1822                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1823                        }
1824
1825                        Trace.asyncTraceEnd(
1826                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1827
1828                        processPendingInstall(args, ret);
1829                        mHandler.sendEmptyMessage(MCS_UNBIND);
1830                    }
1831
1832                    break;
1833                }
1834                case START_INTENT_FILTER_VERIFICATIONS: {
1835                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1836                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1837                            params.replacing, params.pkg);
1838                    break;
1839                }
1840                case INTENT_FILTER_VERIFIED: {
1841                    final int verificationId = msg.arg1;
1842
1843                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1844                            verificationId);
1845                    if (state == null) {
1846                        Slog.w(TAG, "Invalid IntentFilter verification token "
1847                                + verificationId + " received");
1848                        break;
1849                    }
1850
1851                    final int userId = state.getUserId();
1852
1853                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1854                            "Processing IntentFilter verification with token:"
1855                            + verificationId + " and userId:" + userId);
1856
1857                    final IntentFilterVerificationResponse response =
1858                            (IntentFilterVerificationResponse) msg.obj;
1859
1860                    state.setVerifierResponse(response.callerUid, response.code);
1861
1862                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1863                            "IntentFilter verification with token:" + verificationId
1864                            + " and userId:" + userId
1865                            + " is settings verifier response with response code:"
1866                            + response.code);
1867
1868                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1870                                + response.getFailedDomainsString());
1871                    }
1872
1873                    if (state.isVerificationComplete()) {
1874                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1875                    } else {
1876                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                                "IntentFilter verification with token:" + verificationId
1878                                + " was not said to be complete");
1879                    }
1880
1881                    break;
1882                }
1883                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1884                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1885                            mInstantAppResolverConnection,
1886                            (InstantAppRequest) msg.obj,
1887                            mInstantAppInstallerActivity,
1888                            mHandler);
1889                }
1890            }
1891        }
1892    }
1893
1894    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1895            boolean killApp, String[] grantedPermissions,
1896            boolean launchedForRestore, String installerPackage,
1897            IPackageInstallObserver2 installObserver) {
1898        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1899            // Send the removed broadcasts
1900            if (res.removedInfo != null) {
1901                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1902            }
1903
1904            // Now that we successfully installed the package, grant runtime
1905            // permissions if requested before broadcasting the install. Also
1906            // for legacy apps in permission review mode we clear the permission
1907            // review flag which is used to emulate runtime permissions for
1908            // legacy apps.
1909            if (grantPermissions) {
1910                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1911            }
1912
1913            final boolean update = res.removedInfo != null
1914                    && res.removedInfo.removedPackage != null;
1915            final String origInstallerPackageName = res.removedInfo != null
1916                    ? res.removedInfo.installerPackageName : null;
1917
1918            // If this is the first time we have child packages for a disabled privileged
1919            // app that had no children, we grant requested runtime permissions to the new
1920            // children if the parent on the system image had them already granted.
1921            if (res.pkg.parentPackage != null) {
1922                synchronized (mPackages) {
1923                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1924                }
1925            }
1926
1927            synchronized (mPackages) {
1928                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1929            }
1930
1931            final String packageName = res.pkg.applicationInfo.packageName;
1932
1933            // Determine the set of users who are adding this package for
1934            // the first time vs. those who are seeing an update.
1935            int[] firstUsers = EMPTY_INT_ARRAY;
1936            int[] updateUsers = EMPTY_INT_ARRAY;
1937            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1938            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1939            for (int newUser : res.newUsers) {
1940                if (ps.getInstantApp(newUser)) {
1941                    continue;
1942                }
1943                if (allNewUsers) {
1944                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1945                    continue;
1946                }
1947                boolean isNew = true;
1948                for (int origUser : res.origUsers) {
1949                    if (origUser == newUser) {
1950                        isNew = false;
1951                        break;
1952                    }
1953                }
1954                if (isNew) {
1955                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1956                } else {
1957                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1958                }
1959            }
1960
1961            // Send installed broadcasts if the package is not a static shared lib.
1962            if (res.pkg.staticSharedLibName == null) {
1963                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1964
1965                // Send added for users that see the package for the first time
1966                // sendPackageAddedForNewUsers also deals with system apps
1967                int appId = UserHandle.getAppId(res.uid);
1968                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1969                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1970
1971                // Send added for users that don't see the package for the first time
1972                Bundle extras = new Bundle(1);
1973                extras.putInt(Intent.EXTRA_UID, res.uid);
1974                if (update) {
1975                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1976                }
1977                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1978                        extras, 0 /*flags*/,
1979                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1980                if (origInstallerPackageName != null) {
1981                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1982                            extras, 0 /*flags*/,
1983                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1984                }
1985
1986                // Send replaced for users that don't see the package for the first time
1987                if (update) {
1988                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1989                            packageName, extras, 0 /*flags*/,
1990                            null /*targetPackage*/, null /*finishedReceiver*/,
1991                            updateUsers);
1992                    if (origInstallerPackageName != null) {
1993                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1994                                extras, 0 /*flags*/,
1995                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1996                    }
1997                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1998                            null /*package*/, null /*extras*/, 0 /*flags*/,
1999                            packageName /*targetPackage*/,
2000                            null /*finishedReceiver*/, updateUsers);
2001                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2002                    // First-install and we did a restore, so we're responsible for the
2003                    // first-launch broadcast.
2004                    if (DEBUG_BACKUP) {
2005                        Slog.i(TAG, "Post-restore of " + packageName
2006                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2007                    }
2008                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2009                }
2010
2011                // Send broadcast package appeared if forward locked/external for all users
2012                // treat asec-hosted packages like removable media on upgrade
2013                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2014                    if (DEBUG_INSTALL) {
2015                        Slog.i(TAG, "upgrading pkg " + res.pkg
2016                                + " is ASEC-hosted -> AVAILABLE");
2017                    }
2018                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2019                    ArrayList<String> pkgList = new ArrayList<>(1);
2020                    pkgList.add(packageName);
2021                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2022                }
2023            }
2024
2025            // Work that needs to happen on first install within each user
2026            if (firstUsers != null && firstUsers.length > 0) {
2027                synchronized (mPackages) {
2028                    for (int userId : firstUsers) {
2029                        // If this app is a browser and it's newly-installed for some
2030                        // users, clear any default-browser state in those users. The
2031                        // app's nature doesn't depend on the user, so we can just check
2032                        // its browser nature in any user and generalize.
2033                        if (packageIsBrowser(packageName, userId)) {
2034                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2035                        }
2036
2037                        // We may also need to apply pending (restored) runtime
2038                        // permission grants within these users.
2039                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2040                    }
2041                }
2042            }
2043
2044            // Log current value of "unknown sources" setting
2045            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2046                    getUnknownSourcesSettings());
2047
2048            // Remove the replaced package's older resources safely now
2049            // We delete after a gc for applications  on sdcard.
2050            if (res.removedInfo != null && res.removedInfo.args != null) {
2051                Runtime.getRuntime().gc();
2052                synchronized (mInstallLock) {
2053                    res.removedInfo.args.doPostDeleteLI(true);
2054                }
2055            } else {
2056                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2057                // and not block here.
2058                VMRuntime.getRuntime().requestConcurrentGC();
2059            }
2060
2061            // Notify DexManager that the package was installed for new users.
2062            // The updated users should already be indexed and the package code paths
2063            // should not change.
2064            // Don't notify the manager for ephemeral apps as they are not expected to
2065            // survive long enough to benefit of background optimizations.
2066            for (int userId : firstUsers) {
2067                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2068                // There's a race currently where some install events may interleave with an uninstall.
2069                // This can lead to package info being null (b/36642664).
2070                if (info != null) {
2071                    mDexManager.notifyPackageInstalled(info, userId);
2072                }
2073            }
2074        }
2075
2076        // If someone is watching installs - notify them
2077        if (installObserver != null) {
2078            try {
2079                Bundle extras = extrasForInstallResult(res);
2080                installObserver.onPackageInstalled(res.name, res.returnCode,
2081                        res.returnMsg, extras);
2082            } catch (RemoteException e) {
2083                Slog.i(TAG, "Observer no longer exists.");
2084            }
2085        }
2086    }
2087
2088    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2089            PackageParser.Package pkg) {
2090        if (pkg.parentPackage == null) {
2091            return;
2092        }
2093        if (pkg.requestedPermissions == null) {
2094            return;
2095        }
2096        final PackageSetting disabledSysParentPs = mSettings
2097                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2098        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2099                || !disabledSysParentPs.isPrivileged()
2100                || (disabledSysParentPs.childPackageNames != null
2101                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2102            return;
2103        }
2104        final int[] allUserIds = sUserManager.getUserIds();
2105        final int permCount = pkg.requestedPermissions.size();
2106        for (int i = 0; i < permCount; i++) {
2107            String permission = pkg.requestedPermissions.get(i);
2108            BasePermission bp = mSettings.mPermissions.get(permission);
2109            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2110                continue;
2111            }
2112            for (int userId : allUserIds) {
2113                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2114                        permission, userId)) {
2115                    grantRuntimePermission(pkg.packageName, permission, userId);
2116                }
2117            }
2118        }
2119    }
2120
2121    private StorageEventListener mStorageListener = new StorageEventListener() {
2122        @Override
2123        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2124            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2125                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2126                    final String volumeUuid = vol.getFsUuid();
2127
2128                    // Clean up any users or apps that were removed or recreated
2129                    // while this volume was missing
2130                    sUserManager.reconcileUsers(volumeUuid);
2131                    reconcileApps(volumeUuid);
2132
2133                    // Clean up any install sessions that expired or were
2134                    // cancelled while this volume was missing
2135                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2136
2137                    loadPrivatePackages(vol);
2138
2139                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2140                    unloadPrivatePackages(vol);
2141                }
2142            }
2143
2144            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2145                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2146                    updateExternalMediaStatus(true, false);
2147                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2148                    updateExternalMediaStatus(false, false);
2149                }
2150            }
2151        }
2152
2153        @Override
2154        public void onVolumeForgotten(String fsUuid) {
2155            if (TextUtils.isEmpty(fsUuid)) {
2156                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2157                return;
2158            }
2159
2160            // Remove any apps installed on the forgotten volume
2161            synchronized (mPackages) {
2162                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2163                for (PackageSetting ps : packages) {
2164                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2165                    deletePackageVersioned(new VersionedPackage(ps.name,
2166                            PackageManager.VERSION_CODE_HIGHEST),
2167                            new LegacyPackageDeleteObserver(null).getBinder(),
2168                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2169                    // Try very hard to release any references to this package
2170                    // so we don't risk the system server being killed due to
2171                    // open FDs
2172                    AttributeCache.instance().removePackage(ps.name);
2173                }
2174
2175                mSettings.onVolumeForgotten(fsUuid);
2176                mSettings.writeLPr();
2177            }
2178        }
2179    };
2180
2181    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2182            String[] grantedPermissions) {
2183        for (int userId : userIds) {
2184            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2185        }
2186    }
2187
2188    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2189            String[] grantedPermissions) {
2190        SettingBase sb = (SettingBase) pkg.mExtras;
2191        if (sb == null) {
2192            return;
2193        }
2194
2195        PermissionsState permissionsState = sb.getPermissionsState();
2196
2197        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2198                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2199
2200        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2201                >= Build.VERSION_CODES.M;
2202
2203        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2204
2205        for (String permission : pkg.requestedPermissions) {
2206            final BasePermission bp;
2207            synchronized (mPackages) {
2208                bp = mSettings.mPermissions.get(permission);
2209            }
2210            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2211                    && (!instantApp || bp.isInstant())
2212                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2213                    && (grantedPermissions == null
2214                           || ArrayUtils.contains(grantedPermissions, permission))) {
2215                final int flags = permissionsState.getPermissionFlags(permission, userId);
2216                if (supportsRuntimePermissions) {
2217                    // Installer cannot change immutable permissions.
2218                    if ((flags & immutableFlags) == 0) {
2219                        grantRuntimePermission(pkg.packageName, permission, userId);
2220                    }
2221                } else if (mPermissionReviewRequired) {
2222                    // In permission review mode we clear the review flag when we
2223                    // are asked to install the app with all permissions granted.
2224                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2225                        updatePermissionFlags(permission, pkg.packageName,
2226                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2227                    }
2228                }
2229            }
2230        }
2231    }
2232
2233    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2234        Bundle extras = null;
2235        switch (res.returnCode) {
2236            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2237                extras = new Bundle();
2238                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2239                        res.origPermission);
2240                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2241                        res.origPackage);
2242                break;
2243            }
2244            case PackageManager.INSTALL_SUCCEEDED: {
2245                extras = new Bundle();
2246                extras.putBoolean(Intent.EXTRA_REPLACING,
2247                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2248                break;
2249            }
2250        }
2251        return extras;
2252    }
2253
2254    void scheduleWriteSettingsLocked() {
2255        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2256            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2257        }
2258    }
2259
2260    void scheduleWritePackageListLocked(int userId) {
2261        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2262            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2263            msg.arg1 = userId;
2264            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2265        }
2266    }
2267
2268    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2269        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2270        scheduleWritePackageRestrictionsLocked(userId);
2271    }
2272
2273    void scheduleWritePackageRestrictionsLocked(int userId) {
2274        final int[] userIds = (userId == UserHandle.USER_ALL)
2275                ? sUserManager.getUserIds() : new int[]{userId};
2276        for (int nextUserId : userIds) {
2277            if (!sUserManager.exists(nextUserId)) return;
2278            mDirtyUsers.add(nextUserId);
2279            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2280                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2281            }
2282        }
2283    }
2284
2285    public static PackageManagerService main(Context context, Installer installer,
2286            boolean factoryTest, boolean onlyCore) {
2287        // Self-check for initial settings.
2288        PackageManagerServiceCompilerMapping.checkProperties();
2289
2290        PackageManagerService m = new PackageManagerService(context, installer,
2291                factoryTest, onlyCore);
2292        m.enableSystemUserPackages();
2293        ServiceManager.addService("package", m);
2294        return m;
2295    }
2296
2297    private void enableSystemUserPackages() {
2298        if (!UserManager.isSplitSystemUser()) {
2299            return;
2300        }
2301        // For system user, enable apps based on the following conditions:
2302        // - app is whitelisted or belong to one of these groups:
2303        //   -- system app which has no launcher icons
2304        //   -- system app which has INTERACT_ACROSS_USERS permission
2305        //   -- system IME app
2306        // - app is not in the blacklist
2307        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2308        Set<String> enableApps = new ArraySet<>();
2309        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2310                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2311                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2312        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2313        enableApps.addAll(wlApps);
2314        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2315                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2316        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2317        enableApps.removeAll(blApps);
2318        Log.i(TAG, "Applications installed for system user: " + enableApps);
2319        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2320                UserHandle.SYSTEM);
2321        final int allAppsSize = allAps.size();
2322        synchronized (mPackages) {
2323            for (int i = 0; i < allAppsSize; i++) {
2324                String pName = allAps.get(i);
2325                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2326                // Should not happen, but we shouldn't be failing if it does
2327                if (pkgSetting == null) {
2328                    continue;
2329                }
2330                boolean install = enableApps.contains(pName);
2331                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2332                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2333                            + " for system user");
2334                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2335                }
2336            }
2337            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2338        }
2339    }
2340
2341    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2342        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2343                Context.DISPLAY_SERVICE);
2344        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2345    }
2346
2347    /**
2348     * Requests that files preopted on a secondary system partition be copied to the data partition
2349     * if possible.  Note that the actual copying of the files is accomplished by init for security
2350     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2351     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2352     */
2353    private static void requestCopyPreoptedFiles() {
2354        final int WAIT_TIME_MS = 100;
2355        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2356        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2357            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2358            // We will wait for up to 100 seconds.
2359            final long timeStart = SystemClock.uptimeMillis();
2360            final long timeEnd = timeStart + 100 * 1000;
2361            long timeNow = timeStart;
2362            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2363                try {
2364                    Thread.sleep(WAIT_TIME_MS);
2365                } catch (InterruptedException e) {
2366                    // Do nothing
2367                }
2368                timeNow = SystemClock.uptimeMillis();
2369                if (timeNow > timeEnd) {
2370                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2371                    Slog.wtf(TAG, "cppreopt did not finish!");
2372                    break;
2373                }
2374            }
2375
2376            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2377        }
2378    }
2379
2380    public PackageManagerService(Context context, Installer installer,
2381            boolean factoryTest, boolean onlyCore) {
2382        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2383        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2384        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2385                SystemClock.uptimeMillis());
2386
2387        if (mSdkVersion <= 0) {
2388            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2389        }
2390
2391        mContext = context;
2392
2393        mPermissionReviewRequired = context.getResources().getBoolean(
2394                R.bool.config_permissionReviewRequired);
2395
2396        mFactoryTest = factoryTest;
2397        mOnlyCore = onlyCore;
2398        mMetrics = new DisplayMetrics();
2399        mSettings = new Settings(mPackages);
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412
2413        String separateProcesses = SystemProperties.get("debug.separate_processes");
2414        if (separateProcesses != null && separateProcesses.length() > 0) {
2415            if ("*".equals(separateProcesses)) {
2416                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2417                mSeparateProcesses = null;
2418                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2419            } else {
2420                mDefParseFlags = 0;
2421                mSeparateProcesses = separateProcesses.split(",");
2422                Slog.w(TAG, "Running with debug.separate_processes: "
2423                        + separateProcesses);
2424            }
2425        } else {
2426            mDefParseFlags = 0;
2427            mSeparateProcesses = null;
2428        }
2429
2430        mInstaller = installer;
2431        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2432                "*dexopt*");
2433        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2434        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2435
2436        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2437                FgThread.get().getLooper());
2438
2439        getDefaultDisplayMetrics(context, mMetrics);
2440
2441        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2442        SystemConfig systemConfig = SystemConfig.getInstance();
2443        mGlobalGids = systemConfig.getGlobalGids();
2444        mSystemPermissions = systemConfig.getSystemPermissions();
2445        mAvailableFeatures = systemConfig.getAvailableFeatures();
2446        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2447
2448        mProtectedPackages = new ProtectedPackages(mContext);
2449
2450        synchronized (mInstallLock) {
2451        // writer
2452        synchronized (mPackages) {
2453            mHandlerThread = new ServiceThread(TAG,
2454                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2455            mHandlerThread.start();
2456            mHandler = new PackageHandler(mHandlerThread.getLooper());
2457            mProcessLoggingHandler = new ProcessLoggingHandler();
2458            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2459
2460            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2461            mInstantAppRegistry = new InstantAppRegistry(this);
2462
2463            File dataDir = Environment.getDataDirectory();
2464            mAppInstallDir = new File(dataDir, "app");
2465            mAppLib32InstallDir = new File(dataDir, "app-lib");
2466            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2467            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2468            sUserManager = new UserManagerService(context, this,
2469                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2470
2471            // Propagate permission configuration in to package manager.
2472            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2473                    = systemConfig.getPermissions();
2474            for (int i=0; i<permConfig.size(); i++) {
2475                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2476                BasePermission bp = mSettings.mPermissions.get(perm.name);
2477                if (bp == null) {
2478                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2479                    mSettings.mPermissions.put(perm.name, bp);
2480                }
2481                if (perm.gids != null) {
2482                    bp.setGids(perm.gids, perm.perUser);
2483                }
2484            }
2485
2486            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2487            final int builtInLibCount = libConfig.size();
2488            for (int i = 0; i < builtInLibCount; i++) {
2489                String name = libConfig.keyAt(i);
2490                String path = libConfig.valueAt(i);
2491                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2492                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2493            }
2494
2495            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2496
2497            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2498            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2500
2501            // Clean up orphaned packages for which the code path doesn't exist
2502            // and they are an update to a system app - caused by bug/32321269
2503            final int packageSettingCount = mSettings.mPackages.size();
2504            for (int i = packageSettingCount - 1; i >= 0; i--) {
2505                PackageSetting ps = mSettings.mPackages.valueAt(i);
2506                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2507                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2508                    mSettings.mPackages.removeAt(i);
2509                    mSettings.enableSystemPackageLPw(ps.name);
2510                }
2511            }
2512
2513            if (mFirstBoot) {
2514                requestCopyPreoptedFiles();
2515            }
2516
2517            String customResolverActivity = Resources.getSystem().getString(
2518                    R.string.config_customResolverActivity);
2519            if (TextUtils.isEmpty(customResolverActivity)) {
2520                customResolverActivity = null;
2521            } else {
2522                mCustomResolverComponentName = ComponentName.unflattenFromString(
2523                        customResolverActivity);
2524            }
2525
2526            long startTime = SystemClock.uptimeMillis();
2527
2528            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2529                    startTime);
2530
2531            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2532            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2533
2534            if (bootClassPath == null) {
2535                Slog.w(TAG, "No BOOTCLASSPATH found!");
2536            }
2537
2538            if (systemServerClassPath == null) {
2539                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2540            }
2541
2542            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2543
2544            final VersionInfo ver = mSettings.getInternalVersion();
2545            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2546            if (mIsUpgrade) {
2547                logCriticalInfo(Log.INFO,
2548                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2549            }
2550
2551            // when upgrading from pre-M, promote system app permissions from install to runtime
2552            mPromoteSystemApps =
2553                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2554
2555            // When upgrading from pre-N, we need to handle package extraction like first boot,
2556            // as there is no profiling data available.
2557            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2558
2559            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2560
2561            // save off the names of pre-existing system packages prior to scanning; we don't
2562            // want to automatically grant runtime permissions for new system apps
2563            if (mPromoteSystemApps) {
2564                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2565                while (pkgSettingIter.hasNext()) {
2566                    PackageSetting ps = pkgSettingIter.next();
2567                    if (isSystemApp(ps)) {
2568                        mExistingSystemPackages.add(ps.name);
2569                    }
2570                }
2571            }
2572
2573            mCacheDir = preparePackageParserCache(mIsUpgrade);
2574
2575            // Set flag to monitor and not change apk file paths when
2576            // scanning install directories.
2577            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2578
2579            if (mIsUpgrade || mFirstBoot) {
2580                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2581            }
2582
2583            // Collect vendor overlay packages. (Do this before scanning any apps.)
2584            // For security and version matching reason, only consider
2585            // overlay packages if they reside in the right directory.
2586            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR
2589                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2590
2591            mParallelPackageParserCallback.findStaticOverlayPackages();
2592
2593            // Find base frameworks (resource packages without code).
2594            scanDirTracedLI(frameworkDir, mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR
2597                    | PackageParser.PARSE_IS_PRIVILEGED,
2598                    scanFlags | SCAN_NO_DEX, 0);
2599
2600            // Collected privileged system packages.
2601            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2602            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2606
2607            // Collect ordinary system packages.
2608            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2609            scanDirTracedLI(systemAppDir, mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2612
2613            // Collect all vendor packages.
2614            File vendorAppDir = new File("/vendor/app");
2615            try {
2616                vendorAppDir = vendorAppDir.getCanonicalFile();
2617            } catch (IOException e) {
2618                // failed to look up canonical path, continue with original one
2619            }
2620            scanDirTracedLI(vendorAppDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2623
2624            // Collect all OEM packages.
2625            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2626            scanDirTracedLI(oemAppDir, mDefParseFlags
2627                    | PackageParser.PARSE_IS_SYSTEM
2628                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2629
2630            // Prune any system packages that no longer exist.
2631            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2632            if (!mOnlyCore) {
2633                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2634                while (psit.hasNext()) {
2635                    PackageSetting ps = psit.next();
2636
2637                    /*
2638                     * If this is not a system app, it can't be a
2639                     * disable system app.
2640                     */
2641                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2642                        continue;
2643                    }
2644
2645                    /*
2646                     * If the package is scanned, it's not erased.
2647                     */
2648                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2649                    if (scannedPkg != null) {
2650                        /*
2651                         * If the system app is both scanned and in the
2652                         * disabled packages list, then it must have been
2653                         * added via OTA. Remove it from the currently
2654                         * scanned package so the previously user-installed
2655                         * application can be scanned.
2656                         */
2657                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2658                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2659                                    + ps.name + "; removing system app.  Last known codePath="
2660                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2661                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2662                                    + scannedPkg.mVersionCode);
2663                            removePackageLI(scannedPkg, true);
2664                            mExpectingBetter.put(ps.name, ps.codePath);
2665                        }
2666
2667                        continue;
2668                    }
2669
2670                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2671                        psit.remove();
2672                        logCriticalInfo(Log.WARN, "System package " + ps.name
2673                                + " no longer exists; it's data will be wiped");
2674                        // Actual deletion of code and data will be handled by later
2675                        // reconciliation step
2676                    } else {
2677                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2678                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2679                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2680                        }
2681                    }
2682                }
2683            }
2684
2685            //look for any incomplete package installations
2686            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2687            for (int i = 0; i < deletePkgsList.size(); i++) {
2688                // Actual deletion of code and data will be handled by later
2689                // reconciliation step
2690                final String packageName = deletePkgsList.get(i).name;
2691                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2692                synchronized (mPackages) {
2693                    mSettings.removePackageLPw(packageName);
2694                }
2695            }
2696
2697            //delete tmp files
2698            deleteTempPackageFiles();
2699
2700            // Remove any shared userIDs that have no associated packages
2701            mSettings.pruneSharedUsersLPw();
2702
2703            if (!mOnlyCore) {
2704                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2705                        SystemClock.uptimeMillis());
2706                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2707
2708                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2709                        | PackageParser.PARSE_FORWARD_LOCK,
2710                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2711
2712                /**
2713                 * Remove disable package settings for any updated system
2714                 * apps that were removed via an OTA. If they're not a
2715                 * previously-updated app, remove them completely.
2716                 * Otherwise, just revoke their system-level permissions.
2717                 */
2718                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2719                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2720                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2721
2722                    String msg;
2723                    if (deletedPkg == null) {
2724                        msg = "Updated system package " + deletedAppName
2725                                + " no longer exists; it's data will be wiped";
2726                        // Actual deletion of code and data will be handled by later
2727                        // reconciliation step
2728                    } else {
2729                        msg = "Updated system app + " + deletedAppName
2730                                + " no longer present; removing system privileges for "
2731                                + deletedAppName;
2732
2733                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2734
2735                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2736                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2737                    }
2738                    logCriticalInfo(Log.WARN, msg);
2739                }
2740
2741                /**
2742                 * Make sure all system apps that we expected to appear on
2743                 * the userdata partition actually showed up. If they never
2744                 * appeared, crawl back and revive the system version.
2745                 */
2746                for (int i = 0; i < mExpectingBetter.size(); i++) {
2747                    final String packageName = mExpectingBetter.keyAt(i);
2748                    if (!mPackages.containsKey(packageName)) {
2749                        final File scanFile = mExpectingBetter.valueAt(i);
2750
2751                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2752                                + " but never showed up; reverting to system");
2753
2754                        int reparseFlags = mDefParseFlags;
2755                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2756                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2757                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2758                                    | PackageParser.PARSE_IS_PRIVILEGED;
2759                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2760                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2761                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2762                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2763                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2764                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2765                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2766                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2767                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2768                        } else {
2769                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2770                            continue;
2771                        }
2772
2773                        mSettings.enableSystemPackageLPw(packageName);
2774
2775                        try {
2776                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2777                        } catch (PackageManagerException e) {
2778                            Slog.e(TAG, "Failed to parse original system package: "
2779                                    + e.getMessage());
2780                        }
2781                    }
2782                }
2783            }
2784            mExpectingBetter.clear();
2785
2786            // Resolve the storage manager.
2787            mStorageManagerPackage = getStorageManagerPackageName();
2788
2789            // Resolve protected action filters. Only the setup wizard is allowed to
2790            // have a high priority filter for these actions.
2791            mSetupWizardPackage = getSetupWizardPackageName();
2792            if (mProtectedFilters.size() > 0) {
2793                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2794                    Slog.i(TAG, "No setup wizard;"
2795                        + " All protected intents capped to priority 0");
2796                }
2797                for (ActivityIntentInfo filter : mProtectedFilters) {
2798                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2799                        if (DEBUG_FILTERS) {
2800                            Slog.i(TAG, "Found setup wizard;"
2801                                + " allow priority " + filter.getPriority() + ";"
2802                                + " package: " + filter.activity.info.packageName
2803                                + " activity: " + filter.activity.className
2804                                + " priority: " + filter.getPriority());
2805                        }
2806                        // skip setup wizard; allow it to keep the high priority filter
2807                        continue;
2808                    }
2809                    if (DEBUG_FILTERS) {
2810                        Slog.i(TAG, "Protected action; cap priority to 0;"
2811                                + " package: " + filter.activity.info.packageName
2812                                + " activity: " + filter.activity.className
2813                                + " origPrio: " + filter.getPriority());
2814                    }
2815                    filter.setPriority(0);
2816                }
2817            }
2818            mDeferProtectedFilters = false;
2819            mProtectedFilters.clear();
2820
2821            // Now that we know all of the shared libraries, update all clients to have
2822            // the correct library paths.
2823            updateAllSharedLibrariesLPw(null);
2824
2825            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2826                // NOTE: We ignore potential failures here during a system scan (like
2827                // the rest of the commands above) because there's precious little we
2828                // can do about it. A settings error is reported, though.
2829                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2830            }
2831
2832            // Now that we know all the packages we are keeping,
2833            // read and update their last usage times.
2834            mPackageUsage.read(mPackages);
2835            mCompilerStats.read();
2836
2837            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2838                    SystemClock.uptimeMillis());
2839            Slog.i(TAG, "Time to scan packages: "
2840                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2841                    + " seconds");
2842
2843            // If the platform SDK has changed since the last time we booted,
2844            // we need to re-grant app permission to catch any new ones that
2845            // appear.  This is really a hack, and means that apps can in some
2846            // cases get permissions that the user didn't initially explicitly
2847            // allow...  it would be nice to have some better way to handle
2848            // this situation.
2849            int updateFlags = UPDATE_PERMISSIONS_ALL;
2850            if (ver.sdkVersion != mSdkVersion) {
2851                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2852                        + mSdkVersion + "; regranting permissions for internal storage");
2853                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2854            }
2855            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2856            ver.sdkVersion = mSdkVersion;
2857
2858            // If this is the first boot or an update from pre-M, and it is a normal
2859            // boot, then we need to initialize the default preferred apps across
2860            // all defined users.
2861            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2862                for (UserInfo user : sUserManager.getUsers(true)) {
2863                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2864                    applyFactoryDefaultBrowserLPw(user.id);
2865                    primeDomainVerificationsLPw(user.id);
2866                }
2867            }
2868
2869            // Prepare storage for system user really early during boot,
2870            // since core system apps like SettingsProvider and SystemUI
2871            // can't wait for user to start
2872            final int storageFlags;
2873            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2874                storageFlags = StorageManager.FLAG_STORAGE_DE;
2875            } else {
2876                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2877            }
2878            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2879                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2880                    true /* onlyCoreApps */);
2881            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2882                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2883                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2884                traceLog.traceBegin("AppDataFixup");
2885                try {
2886                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2887                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2888                } catch (InstallerException e) {
2889                    Slog.w(TAG, "Trouble fixing GIDs", e);
2890                }
2891                traceLog.traceEnd();
2892
2893                traceLog.traceBegin("AppDataPrepare");
2894                if (deferPackages == null || deferPackages.isEmpty()) {
2895                    return;
2896                }
2897                int count = 0;
2898                for (String pkgName : deferPackages) {
2899                    PackageParser.Package pkg = null;
2900                    synchronized (mPackages) {
2901                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2902                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2903                            pkg = ps.pkg;
2904                        }
2905                    }
2906                    if (pkg != null) {
2907                        synchronized (mInstallLock) {
2908                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2909                                    true /* maybeMigrateAppData */);
2910                        }
2911                        count++;
2912                    }
2913                }
2914                traceLog.traceEnd();
2915                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2916            }, "prepareAppData");
2917
2918            // If this is first boot after an OTA, and a normal boot, then
2919            // we need to clear code cache directories.
2920            // Note that we do *not* clear the application profiles. These remain valid
2921            // across OTAs and are used to drive profile verification (post OTA) and
2922            // profile compilation (without waiting to collect a fresh set of profiles).
2923            if (mIsUpgrade && !onlyCore) {
2924                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2925                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2926                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2927                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2928                        // No apps are running this early, so no need to freeze
2929                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2930                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2931                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2932                    }
2933                }
2934                ver.fingerprint = Build.FINGERPRINT;
2935            }
2936
2937            checkDefaultBrowser();
2938
2939            // clear only after permissions and other defaults have been updated
2940            mExistingSystemPackages.clear();
2941            mPromoteSystemApps = false;
2942
2943            // All the changes are done during package scanning.
2944            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2945
2946            // can downgrade to reader
2947            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2948            mSettings.writeLPr();
2949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2950            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2951                    SystemClock.uptimeMillis());
2952
2953            if (!mOnlyCore) {
2954                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2955                mRequiredInstallerPackage = getRequiredInstallerLPr();
2956                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2957                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2958                if (mIntentFilterVerifierComponent != null) {
2959                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2960                            mIntentFilterVerifierComponent);
2961                } else {
2962                    mIntentFilterVerifier = null;
2963                }
2964                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2965                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2966                        SharedLibraryInfo.VERSION_UNDEFINED);
2967                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2968                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2969                        SharedLibraryInfo.VERSION_UNDEFINED);
2970            } else {
2971                mRequiredVerifierPackage = null;
2972                mRequiredInstallerPackage = null;
2973                mRequiredUninstallerPackage = null;
2974                mIntentFilterVerifierComponent = null;
2975                mIntentFilterVerifier = null;
2976                mServicesSystemSharedLibraryPackageName = null;
2977                mSharedSystemSharedLibraryPackageName = null;
2978            }
2979
2980            mInstallerService = new PackageInstallerService(context, this);
2981            final Pair<ComponentName, String> instantAppResolverComponent =
2982                    getInstantAppResolverLPr();
2983            if (instantAppResolverComponent != null) {
2984                if (DEBUG_EPHEMERAL) {
2985                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2986                }
2987                mInstantAppResolverConnection = new EphemeralResolverConnection(
2988                        mContext, instantAppResolverComponent.first,
2989                        instantAppResolverComponent.second);
2990                mInstantAppResolverSettingsComponent =
2991                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2992            } else {
2993                mInstantAppResolverConnection = null;
2994                mInstantAppResolverSettingsComponent = null;
2995            }
2996            updateInstantAppInstallerLocked(null);
2997
2998            // Read and update the usage of dex files.
2999            // Do this at the end of PM init so that all the packages have their
3000            // data directory reconciled.
3001            // At this point we know the code paths of the packages, so we can validate
3002            // the disk file and build the internal cache.
3003            // The usage file is expected to be small so loading and verifying it
3004            // should take a fairly small time compare to the other activities (e.g. package
3005            // scanning).
3006            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3007            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3008            for (int userId : currentUserIds) {
3009                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3010            }
3011            mDexManager.load(userPackages);
3012        } // synchronized (mPackages)
3013        } // synchronized (mInstallLock)
3014
3015        // Now after opening every single application zip, make sure they
3016        // are all flushed.  Not really needed, but keeps things nice and
3017        // tidy.
3018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3019        Runtime.getRuntime().gc();
3020        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021
3022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3023        FallbackCategoryProvider.loadFallbacks();
3024        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3025
3026        // The initial scanning above does many calls into installd while
3027        // holding the mPackages lock, but we're mostly interested in yelling
3028        // once we have a booted system.
3029        mInstaller.setWarnIfHeld(mPackages);
3030
3031        // Expose private service for system components to use.
3032        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3033        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3034    }
3035
3036    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3037        // we're only interested in updating the installer appliction when 1) it's not
3038        // already set or 2) the modified package is the installer
3039        if (mInstantAppInstallerActivity != null
3040                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3041                        .equals(modifiedPackage)) {
3042            return;
3043        }
3044        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3045    }
3046
3047    private static File preparePackageParserCache(boolean isUpgrade) {
3048        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3049            return null;
3050        }
3051
3052        // Disable package parsing on eng builds to allow for faster incremental development.
3053        if ("eng".equals(Build.TYPE)) {
3054            return null;
3055        }
3056
3057        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3058            Slog.i(TAG, "Disabling package parser cache due to system property.");
3059            return null;
3060        }
3061
3062        // The base directory for the package parser cache lives under /data/system/.
3063        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3064                "package_cache");
3065        if (cacheBaseDir == null) {
3066            return null;
3067        }
3068
3069        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3070        // This also serves to "GC" unused entries when the package cache version changes (which
3071        // can only happen during upgrades).
3072        if (isUpgrade) {
3073            FileUtils.deleteContents(cacheBaseDir);
3074        }
3075
3076
3077        // Return the versioned package cache directory. This is something like
3078        // "/data/system/package_cache/1"
3079        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3080
3081        // The following is a workaround to aid development on non-numbered userdebug
3082        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3083        // the system partition is newer.
3084        //
3085        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3086        // that starts with "eng." to signify that this is an engineering build and not
3087        // destined for release.
3088        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3089            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3090
3091            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3092            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3093            // in general and should not be used for production changes. In this specific case,
3094            // we know that they will work.
3095            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3096            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3097                FileUtils.deleteContents(cacheBaseDir);
3098                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3099            }
3100        }
3101
3102        return cacheDir;
3103    }
3104
3105    @Override
3106    public boolean isFirstBoot() {
3107        // allow instant applications
3108        return mFirstBoot;
3109    }
3110
3111    @Override
3112    public boolean isOnlyCoreApps() {
3113        // allow instant applications
3114        return mOnlyCore;
3115    }
3116
3117    @Override
3118    public boolean isUpgrade() {
3119        // allow instant applications
3120        return mIsUpgrade;
3121    }
3122
3123    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3124        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3125
3126        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3127                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3128                UserHandle.USER_SYSTEM);
3129        if (matches.size() == 1) {
3130            return matches.get(0).getComponentInfo().packageName;
3131        } else if (matches.size() == 0) {
3132            Log.e(TAG, "There should probably be a verifier, but, none were found");
3133            return null;
3134        }
3135        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3136    }
3137
3138    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3139        synchronized (mPackages) {
3140            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3141            if (libraryEntry == null) {
3142                throw new IllegalStateException("Missing required shared library:" + name);
3143            }
3144            return libraryEntry.apk;
3145        }
3146    }
3147
3148    private @NonNull String getRequiredInstallerLPr() {
3149        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3150        intent.addCategory(Intent.CATEGORY_DEFAULT);
3151        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3152
3153        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3154                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3155                UserHandle.USER_SYSTEM);
3156        if (matches.size() == 1) {
3157            ResolveInfo resolveInfo = matches.get(0);
3158            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3159                throw new RuntimeException("The installer must be a privileged app");
3160            }
3161            return matches.get(0).getComponentInfo().packageName;
3162        } else {
3163            throw new RuntimeException("There must be exactly one installer; found " + matches);
3164        }
3165    }
3166
3167    private @NonNull String getRequiredUninstallerLPr() {
3168        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3169        intent.addCategory(Intent.CATEGORY_DEFAULT);
3170        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3171
3172        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3173                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3174                UserHandle.USER_SYSTEM);
3175        if (resolveInfo == null ||
3176                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3177            throw new RuntimeException("There must be exactly one uninstaller; found "
3178                    + resolveInfo);
3179        }
3180        return resolveInfo.getComponentInfo().packageName;
3181    }
3182
3183    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3184        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3185
3186        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3187                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3188                UserHandle.USER_SYSTEM);
3189        ResolveInfo best = null;
3190        final int N = matches.size();
3191        for (int i = 0; i < N; i++) {
3192            final ResolveInfo cur = matches.get(i);
3193            final String packageName = cur.getComponentInfo().packageName;
3194            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3195                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3196                continue;
3197            }
3198
3199            if (best == null || cur.priority > best.priority) {
3200                best = cur;
3201            }
3202        }
3203
3204        if (best != null) {
3205            return best.getComponentInfo().getComponentName();
3206        }
3207        Slog.w(TAG, "Intent filter verifier not found");
3208        return null;
3209    }
3210
3211    @Override
3212    public @Nullable ComponentName getInstantAppResolverComponent() {
3213        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3214            return null;
3215        }
3216        synchronized (mPackages) {
3217            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3218            if (instantAppResolver == null) {
3219                return null;
3220            }
3221            return instantAppResolver.first;
3222        }
3223    }
3224
3225    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3226        final String[] packageArray =
3227                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3228        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3229            if (DEBUG_EPHEMERAL) {
3230                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3231            }
3232            return null;
3233        }
3234
3235        final int callingUid = Binder.getCallingUid();
3236        final int resolveFlags =
3237                MATCH_DIRECT_BOOT_AWARE
3238                | MATCH_DIRECT_BOOT_UNAWARE
3239                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3240        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3241        final Intent resolverIntent = new Intent(actionName);
3242        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3243                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3244        // temporarily look for the old action
3245        if (resolvers.size() == 0) {
3246            if (DEBUG_EPHEMERAL) {
3247                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3248            }
3249            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3250            resolverIntent.setAction(actionName);
3251            resolvers = queryIntentServicesInternal(resolverIntent, null,
3252                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3253        }
3254        final int N = resolvers.size();
3255        if (N == 0) {
3256            if (DEBUG_EPHEMERAL) {
3257                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3258            }
3259            return null;
3260        }
3261
3262        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3263        for (int i = 0; i < N; i++) {
3264            final ResolveInfo info = resolvers.get(i);
3265
3266            if (info.serviceInfo == null) {
3267                continue;
3268            }
3269
3270            final String packageName = info.serviceInfo.packageName;
3271            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3272                if (DEBUG_EPHEMERAL) {
3273                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3274                            + " pkg: " + packageName + ", info:" + info);
3275                }
3276                continue;
3277            }
3278
3279            if (DEBUG_EPHEMERAL) {
3280                Slog.v(TAG, "Ephemeral resolver found;"
3281                        + " pkg: " + packageName + ", info:" + info);
3282            }
3283            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3284        }
3285        if (DEBUG_EPHEMERAL) {
3286            Slog.v(TAG, "Ephemeral resolver NOT found");
3287        }
3288        return null;
3289    }
3290
3291    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3292        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3293        intent.addCategory(Intent.CATEGORY_DEFAULT);
3294        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3295
3296        final int resolveFlags =
3297                MATCH_DIRECT_BOOT_AWARE
3298                | MATCH_DIRECT_BOOT_UNAWARE
3299                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3300        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3301                resolveFlags, UserHandle.USER_SYSTEM);
3302        // temporarily look for the old action
3303        if (matches.isEmpty()) {
3304            if (DEBUG_EPHEMERAL) {
3305                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3306            }
3307            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3308            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3309                    resolveFlags, UserHandle.USER_SYSTEM);
3310        }
3311        Iterator<ResolveInfo> iter = matches.iterator();
3312        while (iter.hasNext()) {
3313            final ResolveInfo rInfo = iter.next();
3314            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3315            if (ps != null) {
3316                final PermissionsState permissionsState = ps.getPermissionsState();
3317                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3318                    continue;
3319                }
3320            }
3321            iter.remove();
3322        }
3323        if (matches.size() == 0) {
3324            return null;
3325        } else if (matches.size() == 1) {
3326            return (ActivityInfo) matches.get(0).getComponentInfo();
3327        } else {
3328            throw new RuntimeException(
3329                    "There must be at most one ephemeral installer; found " + matches);
3330        }
3331    }
3332
3333    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3334            @NonNull ComponentName resolver) {
3335        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3336                .addCategory(Intent.CATEGORY_DEFAULT)
3337                .setPackage(resolver.getPackageName());
3338        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3339        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3340                UserHandle.USER_SYSTEM);
3341        // temporarily look for the old action
3342        if (matches.isEmpty()) {
3343            if (DEBUG_EPHEMERAL) {
3344                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3345            }
3346            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3347            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3348                    UserHandle.USER_SYSTEM);
3349        }
3350        if (matches.isEmpty()) {
3351            return null;
3352        }
3353        return matches.get(0).getComponentInfo().getComponentName();
3354    }
3355
3356    private void primeDomainVerificationsLPw(int userId) {
3357        if (DEBUG_DOMAIN_VERIFICATION) {
3358            Slog.d(TAG, "Priming domain verifications in user " + userId);
3359        }
3360
3361        SystemConfig systemConfig = SystemConfig.getInstance();
3362        ArraySet<String> packages = systemConfig.getLinkedApps();
3363
3364        for (String packageName : packages) {
3365            PackageParser.Package pkg = mPackages.get(packageName);
3366            if (pkg != null) {
3367                if (!pkg.isSystemApp()) {
3368                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3369                    continue;
3370                }
3371
3372                ArraySet<String> domains = null;
3373                for (PackageParser.Activity a : pkg.activities) {
3374                    for (ActivityIntentInfo filter : a.intents) {
3375                        if (hasValidDomains(filter)) {
3376                            if (domains == null) {
3377                                domains = new ArraySet<String>();
3378                            }
3379                            domains.addAll(filter.getHostsList());
3380                        }
3381                    }
3382                }
3383
3384                if (domains != null && domains.size() > 0) {
3385                    if (DEBUG_DOMAIN_VERIFICATION) {
3386                        Slog.v(TAG, "      + " + packageName);
3387                    }
3388                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3389                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3390                    // and then 'always' in the per-user state actually used for intent resolution.
3391                    final IntentFilterVerificationInfo ivi;
3392                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3393                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3394                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3395                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3396                } else {
3397                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3398                            + "' does not handle web links");
3399                }
3400            } else {
3401                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3402            }
3403        }
3404
3405        scheduleWritePackageRestrictionsLocked(userId);
3406        scheduleWriteSettingsLocked();
3407    }
3408
3409    private void applyFactoryDefaultBrowserLPw(int userId) {
3410        // The default browser app's package name is stored in a string resource,
3411        // with a product-specific overlay used for vendor customization.
3412        String browserPkg = mContext.getResources().getString(
3413                com.android.internal.R.string.default_browser);
3414        if (!TextUtils.isEmpty(browserPkg)) {
3415            // non-empty string => required to be a known package
3416            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3417            if (ps == null) {
3418                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3419                browserPkg = null;
3420            } else {
3421                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3422            }
3423        }
3424
3425        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3426        // default.  If there's more than one, just leave everything alone.
3427        if (browserPkg == null) {
3428            calculateDefaultBrowserLPw(userId);
3429        }
3430    }
3431
3432    private void calculateDefaultBrowserLPw(int userId) {
3433        List<String> allBrowsers = resolveAllBrowserApps(userId);
3434        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3435        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3436    }
3437
3438    private List<String> resolveAllBrowserApps(int userId) {
3439        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3440        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3441                PackageManager.MATCH_ALL, userId);
3442
3443        final int count = list.size();
3444        List<String> result = new ArrayList<String>(count);
3445        for (int i=0; i<count; i++) {
3446            ResolveInfo info = list.get(i);
3447            if (info.activityInfo == null
3448                    || !info.handleAllWebDataURI
3449                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3450                    || result.contains(info.activityInfo.packageName)) {
3451                continue;
3452            }
3453            result.add(info.activityInfo.packageName);
3454        }
3455
3456        return result;
3457    }
3458
3459    private boolean packageIsBrowser(String packageName, int userId) {
3460        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3461                PackageManager.MATCH_ALL, userId);
3462        final int N = list.size();
3463        for (int i = 0; i < N; i++) {
3464            ResolveInfo info = list.get(i);
3465            if (packageName.equals(info.activityInfo.packageName)) {
3466                return true;
3467            }
3468        }
3469        return false;
3470    }
3471
3472    private void checkDefaultBrowser() {
3473        final int myUserId = UserHandle.myUserId();
3474        final String packageName = getDefaultBrowserPackageName(myUserId);
3475        if (packageName != null) {
3476            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3477            if (info == null) {
3478                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3479                synchronized (mPackages) {
3480                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3481                }
3482            }
3483        }
3484    }
3485
3486    @Override
3487    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3488            throws RemoteException {
3489        try {
3490            return super.onTransact(code, data, reply, flags);
3491        } catch (RuntimeException e) {
3492            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3493                Slog.wtf(TAG, "Package Manager Crash", e);
3494            }
3495            throw e;
3496        }
3497    }
3498
3499    static int[] appendInts(int[] cur, int[] add) {
3500        if (add == null) return cur;
3501        if (cur == null) return add;
3502        final int N = add.length;
3503        for (int i=0; i<N; i++) {
3504            cur = appendInt(cur, add[i]);
3505        }
3506        return cur;
3507    }
3508
3509    /**
3510     * Returns whether or not a full application can see an instant application.
3511     * <p>
3512     * Currently, there are three cases in which this can occur:
3513     * <ol>
3514     * <li>The calling application is a "special" process. The special
3515     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3516     *     and {@code 0}</li>
3517     * <li>The calling application has the permission
3518     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3519     * <li>[TODO] The calling application is the default launcher on the
3520     *     system partition.</li>
3521     * </ol>
3522     */
3523    private boolean canViewInstantApps(int callingUid, int userId) {
3524        if (callingUid == Process.SYSTEM_UID
3525                || callingUid == Process.SHELL_UID
3526                || callingUid == Process.ROOT_UID) {
3527            return true;
3528        }
3529        if (mContext.checkCallingOrSelfPermission(
3530                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3531            return true;
3532        }
3533        if (mContext.checkCallingOrSelfPermission(
3534                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3535            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3536            if (homeComponent != null
3537                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3538                return true;
3539            }
3540        }
3541        return false;
3542    }
3543
3544    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3545        if (!sUserManager.exists(userId)) return null;
3546        if (ps == null) {
3547            return null;
3548        }
3549        PackageParser.Package p = ps.pkg;
3550        if (p == null) {
3551            return null;
3552        }
3553        final int callingUid = Binder.getCallingUid();
3554        // Filter out ephemeral app metadata:
3555        //   * The system/shell/root can see metadata for any app
3556        //   * An installed app can see metadata for 1) other installed apps
3557        //     and 2) ephemeral apps that have explicitly interacted with it
3558        //   * Ephemeral apps can only see their own data and exposed installed apps
3559        //   * Holding a signature permission allows seeing instant apps
3560        if (filterAppAccessLPr(ps, callingUid, userId)) {
3561            return null;
3562        }
3563
3564        final PermissionsState permissionsState = ps.getPermissionsState();
3565
3566        // Compute GIDs only if requested
3567        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3568                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3569        // Compute granted permissions only if package has requested permissions
3570        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3571                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3572        final PackageUserState state = ps.readUserState(userId);
3573
3574        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3575                && ps.isSystem()) {
3576            flags |= MATCH_ANY_USER;
3577        }
3578
3579        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3580                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3581
3582        if (packageInfo == null) {
3583            return null;
3584        }
3585
3586        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3587
3588        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3589                resolveExternalPackageNameLPr(p);
3590
3591        return packageInfo;
3592    }
3593
3594    @Override
3595    public void checkPackageStartable(String packageName, int userId) {
3596        final int callingUid = Binder.getCallingUid();
3597        if (getInstantAppPackageName(callingUid) != null) {
3598            throw new SecurityException("Instant applications don't have access to this method");
3599        }
3600        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3601        synchronized (mPackages) {
3602            final PackageSetting ps = mSettings.mPackages.get(packageName);
3603            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3604                throw new SecurityException("Package " + packageName + " was not found!");
3605            }
3606
3607            if (!ps.getInstalled(userId)) {
3608                throw new SecurityException(
3609                        "Package " + packageName + " was not installed for user " + userId + "!");
3610            }
3611
3612            if (mSafeMode && !ps.isSystem()) {
3613                throw new SecurityException("Package " + packageName + " not a system app!");
3614            }
3615
3616            if (mFrozenPackages.contains(packageName)) {
3617                throw new SecurityException("Package " + packageName + " is currently frozen!");
3618            }
3619
3620            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3621                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3622                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3623            }
3624        }
3625    }
3626
3627    @Override
3628    public boolean isPackageAvailable(String packageName, int userId) {
3629        if (!sUserManager.exists(userId)) return false;
3630        final int callingUid = Binder.getCallingUid();
3631        enforceCrossUserPermission(callingUid, userId,
3632                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3633        synchronized (mPackages) {
3634            PackageParser.Package p = mPackages.get(packageName);
3635            if (p != null) {
3636                final PackageSetting ps = (PackageSetting) p.mExtras;
3637                if (filterAppAccessLPr(ps, callingUid, userId)) {
3638                    return false;
3639                }
3640                if (ps != null) {
3641                    final PackageUserState state = ps.readUserState(userId);
3642                    if (state != null) {
3643                        return PackageParser.isAvailable(state);
3644                    }
3645                }
3646            }
3647        }
3648        return false;
3649    }
3650
3651    @Override
3652    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3653        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3654                flags, userId);
3655    }
3656
3657    @Override
3658    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3659            int flags, int userId) {
3660        return getPackageInfoInternal(versionedPackage.getPackageName(),
3661                versionedPackage.getVersionCode(), flags, userId);
3662    }
3663
3664    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3665            int flags, int userId) {
3666        if (!sUserManager.exists(userId)) return null;
3667        final int callingUid = Binder.getCallingUid();
3668        flags = updateFlagsForPackage(flags, userId, packageName);
3669        enforceCrossUserPermission(callingUid, userId,
3670                false /* requireFullPermission */, false /* checkShell */, "get package info");
3671
3672        // reader
3673        synchronized (mPackages) {
3674            // Normalize package name to handle renamed packages and static libs
3675            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3676
3677            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3678            if (matchFactoryOnly) {
3679                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3680                if (ps != null) {
3681                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3682                        return null;
3683                    }
3684                    if (filterAppAccessLPr(ps, callingUid, userId)) {
3685                        return null;
3686                    }
3687                    return generatePackageInfo(ps, flags, userId);
3688                }
3689            }
3690
3691            PackageParser.Package p = mPackages.get(packageName);
3692            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3693                return null;
3694            }
3695            if (DEBUG_PACKAGE_INFO)
3696                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3697            if (p != null) {
3698                final PackageSetting ps = (PackageSetting) p.mExtras;
3699                if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3700                    return null;
3701                }
3702                if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
3703                    return null;
3704                }
3705                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3706            }
3707            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3708                final PackageSetting ps = mSettings.mPackages.get(packageName);
3709                if (ps == null) return null;
3710                if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3711                    return null;
3712                }
3713                if (filterAppAccessLPr(ps, callingUid, userId)) {
3714                    return null;
3715                }
3716                return generatePackageInfo(ps, flags, userId);
3717            }
3718        }
3719        return null;
3720    }
3721
3722    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3723        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3724            return true;
3725        }
3726        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3727            return true;
3728        }
3729        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3730            return true;
3731        }
3732        return false;
3733    }
3734
3735    private boolean isComponentVisibleToInstantApp(
3736            @Nullable ComponentName component, @ComponentType int type) {
3737        if (type == TYPE_ACTIVITY) {
3738            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3739            return activity != null
3740                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3741                    : false;
3742        } else if (type == TYPE_RECEIVER) {
3743            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3744            return activity != null
3745                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3746                    : false;
3747        } else if (type == TYPE_SERVICE) {
3748            final PackageParser.Service service = mServices.mServices.get(component);
3749            return service != null
3750                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3751                    : false;
3752        } else if (type == TYPE_PROVIDER) {
3753            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3754            return provider != null
3755                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3756                    : false;
3757        } else if (type == TYPE_UNKNOWN) {
3758            return isComponentVisibleToInstantApp(component);
3759        }
3760        return false;
3761    }
3762
3763    /**
3764     * Returns whether or not access to the application should be filtered.
3765     * <p>
3766     * Access may be limited based upon whether the calling or target applications
3767     * are instant applications.
3768     *
3769     * @see #canAccessInstantApps(int)
3770     */
3771    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3772            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3773        // if we're in an isolated process, get the real calling UID
3774        if (Process.isIsolated(callingUid)) {
3775            callingUid = mIsolatedOwners.get(callingUid);
3776        }
3777        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3778        final boolean callerIsInstantApp = instantAppPkgName != null;
3779        if (ps == null) {
3780            if (callerIsInstantApp) {
3781                // pretend the application exists, but, needs to be filtered
3782                return true;
3783            }
3784            return false;
3785        }
3786        // if the target and caller are the same application, don't filter
3787        if (isCallerSameApp(ps.name, callingUid)) {
3788            return false;
3789        }
3790        if (callerIsInstantApp) {
3791            // request for a specific component; if it hasn't been explicitly exposed, filter
3792            if (component != null) {
3793                return !isComponentVisibleToInstantApp(component, componentType);
3794            }
3795            // request for application; if no components have been explicitly exposed, filter
3796            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3797        }
3798        if (ps.getInstantApp(userId)) {
3799            // caller can see all components of all instant applications, don't filter
3800            if (canViewInstantApps(callingUid, userId)) {
3801                return false;
3802            }
3803            // request for a specific instant application component, filter
3804            if (component != null) {
3805                return true;
3806            }
3807            // request for an instant application; if the caller hasn't been granted access, filter
3808            return !mInstantAppRegistry.isInstantAccessGranted(
3809                    userId, UserHandle.getAppId(callingUid), ps.appId);
3810        }
3811        return false;
3812    }
3813
3814    /**
3815     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3816     */
3817    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3818        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3819    }
3820
3821    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3822            int flags) {
3823        // Callers can access only the libs they depend on, otherwise they need to explicitly
3824        // ask for the shared libraries given the caller is allowed to access all static libs.
3825        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3826            // System/shell/root get to see all static libs
3827            final int appId = UserHandle.getAppId(uid);
3828            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3829                    || appId == Process.ROOT_UID) {
3830                return false;
3831            }
3832        }
3833
3834        // No package means no static lib as it is always on internal storage
3835        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3836            return false;
3837        }
3838
3839        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3840                ps.pkg.staticSharedLibVersion);
3841        if (libEntry == null) {
3842            return false;
3843        }
3844
3845        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3846        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3847        if (uidPackageNames == null) {
3848            return true;
3849        }
3850
3851        for (String uidPackageName : uidPackageNames) {
3852            if (ps.name.equals(uidPackageName)) {
3853                return false;
3854            }
3855            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3856            if (uidPs != null) {
3857                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3858                        libEntry.info.getName());
3859                if (index < 0) {
3860                    continue;
3861                }
3862                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3863                    return false;
3864                }
3865            }
3866        }
3867        return true;
3868    }
3869
3870    @Override
3871    public String[] currentToCanonicalPackageNames(String[] names) {
3872        final int callingUid = Binder.getCallingUid();
3873        if (getInstantAppPackageName(callingUid) != null) {
3874            return names;
3875        }
3876        final String[] out = new String[names.length];
3877        // reader
3878        synchronized (mPackages) {
3879            final int callingUserId = UserHandle.getUserId(callingUid);
3880            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3881            for (int i=names.length-1; i>=0; i--) {
3882                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3883                boolean translateName = false;
3884                if (ps != null && ps.realName != null) {
3885                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3886                    translateName = !targetIsInstantApp
3887                            || canViewInstantApps
3888                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3889                                    UserHandle.getAppId(callingUid), ps.appId);
3890                }
3891                out[i] = translateName ? ps.realName : names[i];
3892            }
3893        }
3894        return out;
3895    }
3896
3897    @Override
3898    public String[] canonicalToCurrentPackageNames(String[] names) {
3899        final int callingUid = Binder.getCallingUid();
3900        if (getInstantAppPackageName(callingUid) != null) {
3901            return names;
3902        }
3903        final String[] out = new String[names.length];
3904        // reader
3905        synchronized (mPackages) {
3906            final int callingUserId = UserHandle.getUserId(callingUid);
3907            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3908            for (int i=names.length-1; i>=0; i--) {
3909                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3910                boolean translateName = false;
3911                if (cur != null) {
3912                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3913                    final boolean targetIsInstantApp =
3914                            ps != null && ps.getInstantApp(callingUserId);
3915                    translateName = !targetIsInstantApp
3916                            || canViewInstantApps
3917                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3918                                    UserHandle.getAppId(callingUid), ps.appId);
3919                }
3920                out[i] = translateName ? cur : names[i];
3921            }
3922        }
3923        return out;
3924    }
3925
3926    @Override
3927    public int getPackageUid(String packageName, int flags, int userId) {
3928        if (!sUserManager.exists(userId)) return -1;
3929        final int callingUid = Binder.getCallingUid();
3930        flags = updateFlagsForPackage(flags, userId, packageName);
3931        enforceCrossUserPermission(callingUid, userId,
3932                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3933
3934        // reader
3935        synchronized (mPackages) {
3936            final PackageParser.Package p = mPackages.get(packageName);
3937            if (p != null && p.isMatch(flags)) {
3938                PackageSetting ps = (PackageSetting) p.mExtras;
3939                if (filterAppAccessLPr(ps, callingUid, userId)) {
3940                    return -1;
3941                }
3942                return UserHandle.getUid(userId, p.applicationInfo.uid);
3943            }
3944            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3945                final PackageSetting ps = mSettings.mPackages.get(packageName);
3946                if (ps != null && ps.isMatch(flags)
3947                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3948                    return UserHandle.getUid(userId, ps.appId);
3949                }
3950            }
3951        }
3952
3953        return -1;
3954    }
3955
3956    @Override
3957    public int[] getPackageGids(String packageName, int flags, int userId) {
3958        if (!sUserManager.exists(userId)) return null;
3959        final int callingUid = Binder.getCallingUid();
3960        flags = updateFlagsForPackage(flags, userId, packageName);
3961        enforceCrossUserPermission(callingUid, userId,
3962                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3963
3964        // reader
3965        synchronized (mPackages) {
3966            final PackageParser.Package p = mPackages.get(packageName);
3967            if (p != null && p.isMatch(flags)) {
3968                PackageSetting ps = (PackageSetting) p.mExtras;
3969                if (filterAppAccessLPr(ps, callingUid, userId)) {
3970                    return null;
3971                }
3972                // TODO: Shouldn't this be checking for package installed state for userId and
3973                // return null?
3974                return ps.getPermissionsState().computeGids(userId);
3975            }
3976            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3977                final PackageSetting ps = mSettings.mPackages.get(packageName);
3978                if (ps != null && ps.isMatch(flags)
3979                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3980                    return ps.getPermissionsState().computeGids(userId);
3981                }
3982            }
3983        }
3984
3985        return null;
3986    }
3987
3988    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3989        if (bp.perm != null) {
3990            return PackageParser.generatePermissionInfo(bp.perm, flags);
3991        }
3992        PermissionInfo pi = new PermissionInfo();
3993        pi.name = bp.name;
3994        pi.packageName = bp.sourcePackage;
3995        pi.nonLocalizedLabel = bp.name;
3996        pi.protectionLevel = bp.protectionLevel;
3997        return pi;
3998    }
3999
4000    @Override
4001    public PermissionInfo getPermissionInfo(String name, int flags) {
4002        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4003            return null;
4004        }
4005        // reader
4006        synchronized (mPackages) {
4007            final BasePermission p = mSettings.mPermissions.get(name);
4008            if (p != null) {
4009                return generatePermissionInfo(p, flags);
4010            }
4011            return null;
4012        }
4013    }
4014
4015    @Override
4016    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4017            int flags) {
4018        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4019            return null;
4020        }
4021        // reader
4022        synchronized (mPackages) {
4023            if (group != null && !mPermissionGroups.containsKey(group)) {
4024                // This is thrown as NameNotFoundException
4025                return null;
4026            }
4027
4028            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4029            for (BasePermission p : mSettings.mPermissions.values()) {
4030                if (group == null) {
4031                    if (p.perm == null || p.perm.info.group == null) {
4032                        out.add(generatePermissionInfo(p, flags));
4033                    }
4034                } else {
4035                    if (p.perm != null && group.equals(p.perm.info.group)) {
4036                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4037                    }
4038                }
4039            }
4040            return new ParceledListSlice<>(out);
4041        }
4042    }
4043
4044    @Override
4045    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4046        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4047            return null;
4048        }
4049        // reader
4050        synchronized (mPackages) {
4051            return PackageParser.generatePermissionGroupInfo(
4052                    mPermissionGroups.get(name), flags);
4053        }
4054    }
4055
4056    @Override
4057    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4058        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4059            return ParceledListSlice.emptyList();
4060        }
4061        // reader
4062        synchronized (mPackages) {
4063            final int N = mPermissionGroups.size();
4064            ArrayList<PermissionGroupInfo> out
4065                    = new ArrayList<PermissionGroupInfo>(N);
4066            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4067                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4068            }
4069            return new ParceledListSlice<>(out);
4070        }
4071    }
4072
4073    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4074            int uid, int userId) {
4075        if (!sUserManager.exists(userId)) return null;
4076        PackageSetting ps = mSettings.mPackages.get(packageName);
4077        if (ps != null) {
4078            if (filterSharedLibPackageLPr(ps, uid, userId, flags)) {
4079                return null;
4080            }
4081            if (filterAppAccessLPr(ps, uid, userId)) {
4082                return null;
4083            }
4084            if (ps.pkg == null) {
4085                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4086                if (pInfo != null) {
4087                    return pInfo.applicationInfo;
4088                }
4089                return null;
4090            }
4091            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4092                    ps.readUserState(userId), userId);
4093            if (ai != null) {
4094                rebaseEnabledOverlays(ai, userId);
4095                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4096            }
4097            return ai;
4098        }
4099        return null;
4100    }
4101
4102    @Override
4103    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4104        if (!sUserManager.exists(userId)) return null;
4105        flags = updateFlagsForApplication(flags, userId, packageName);
4106        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4107                false /* requireFullPermission */, false /* checkShell */, "get application info");
4108
4109        // writer
4110        synchronized (mPackages) {
4111            // Normalize package name to handle renamed packages and static libs
4112            packageName = resolveInternalPackageNameLPr(packageName,
4113                    PackageManager.VERSION_CODE_HIGHEST);
4114
4115            PackageParser.Package p = mPackages.get(packageName);
4116            if (DEBUG_PACKAGE_INFO) Log.v(
4117                    TAG, "getApplicationInfo " + packageName
4118                    + ": " + p);
4119            if (p != null) {
4120                PackageSetting ps = mSettings.mPackages.get(packageName);
4121                if (ps == null) return null;
4122                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
4123                    return null;
4124                }
4125                if (filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
4126                    return null;
4127                }
4128                // Note: isEnabledLP() does not apply here - always return info
4129                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4130                        p, flags, ps.readUserState(userId), userId);
4131                if (ai != null) {
4132                    rebaseEnabledOverlays(ai, userId);
4133                    ai.packageName = resolveExternalPackageNameLPr(p);
4134                }
4135                return ai;
4136            }
4137            if ("android".equals(packageName)||"system".equals(packageName)) {
4138                return mAndroidApplication;
4139            }
4140            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4141                // Already generates the external package name
4142                return generateApplicationInfoFromSettingsLPw(packageName,
4143                        Binder.getCallingUid(), flags, userId);
4144            }
4145        }
4146        return null;
4147    }
4148
4149    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
4150        List<String> paths = new ArrayList<>();
4151        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
4152            mEnabledOverlayPaths.get(userId);
4153        if (userSpecificOverlays != null) {
4154            if (!"android".equals(ai.packageName)) {
4155                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
4156                if (frameworkOverlays != null) {
4157                    paths.addAll(frameworkOverlays);
4158                }
4159            }
4160
4161            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
4162            if (appOverlays != null) {
4163                paths.addAll(appOverlays);
4164            }
4165        }
4166        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
4167    }
4168
4169    private String normalizePackageNameLPr(String packageName) {
4170        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4171        return normalizedPackageName != null ? normalizedPackageName : packageName;
4172    }
4173
4174    @Override
4175    public void deletePreloadsFileCache() {
4176        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4177            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4178        }
4179        File dir = Environment.getDataPreloadsFileCacheDirectory();
4180        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4181        FileUtils.deleteContents(dir);
4182    }
4183
4184    @Override
4185    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4186            final int storageFlags, final IPackageDataObserver observer) {
4187        mContext.enforceCallingOrSelfPermission(
4188                android.Manifest.permission.CLEAR_APP_CACHE, null);
4189        mHandler.post(() -> {
4190            boolean success = false;
4191            try {
4192                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4193                success = true;
4194            } catch (IOException e) {
4195                Slog.w(TAG, e);
4196            }
4197            if (observer != null) {
4198                try {
4199                    observer.onRemoveCompleted(null, success);
4200                } catch (RemoteException e) {
4201                    Slog.w(TAG, e);
4202                }
4203            }
4204        });
4205    }
4206
4207    @Override
4208    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4209            final int storageFlags, final IntentSender pi) {
4210        mContext.enforceCallingOrSelfPermission(
4211                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4212        mHandler.post(() -> {
4213            boolean success = false;
4214            try {
4215                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4216                success = true;
4217            } catch (IOException e) {
4218                Slog.w(TAG, e);
4219            }
4220            if (pi != null) {
4221                try {
4222                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4223                } catch (SendIntentException e) {
4224                    Slog.w(TAG, e);
4225                }
4226            }
4227        });
4228    }
4229
4230    /**
4231     * Blocking call to clear various types of cached data across the system
4232     * until the requested bytes are available.
4233     */
4234    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4235        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4236        final File file = storage.findPathForUuid(volumeUuid);
4237        if (file.getUsableSpace() >= bytes) return;
4238
4239        if (ENABLE_FREE_CACHE_V2) {
4240            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4241                    volumeUuid);
4242            final boolean aggressive = (storageFlags
4243                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4244            final boolean defyReserved = (storageFlags
4245                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4246            final long reservedBytes = (aggressive || defyReserved) ? 0
4247                    : storage.getStorageCacheBytes(file);
4248
4249            // 1. Pre-flight to determine if we have any chance to succeed
4250            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4251            if (internalVolume && (aggressive || SystemProperties
4252                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4253                deletePreloadsFileCache();
4254                if (file.getUsableSpace() >= bytes) return;
4255            }
4256
4257            // 3. Consider parsed APK data (aggressive only)
4258            if (internalVolume && aggressive) {
4259                FileUtils.deleteContents(mCacheDir);
4260                if (file.getUsableSpace() >= bytes) return;
4261            }
4262
4263            // 4. Consider cached app data (above quotas)
4264            try {
4265                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4266                        Installer.FLAG_FREE_CACHE_V2);
4267            } catch (InstallerException ignored) {
4268            }
4269            if (file.getUsableSpace() >= bytes) return;
4270
4271            // 5. Consider shared libraries with refcount=0 and age>min cache period
4272            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4273                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4274                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4275                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4276                return;
4277            }
4278
4279            // 6. Consider dexopt output (aggressive only)
4280            // TODO: Implement
4281
4282            // 7. Consider installed instant apps unused longer than min cache period
4283            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4284                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4285                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4286                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4287                return;
4288            }
4289
4290            // 8. Consider cached app data (below quotas)
4291            try {
4292                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4293                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4294            } catch (InstallerException ignored) {
4295            }
4296            if (file.getUsableSpace() >= bytes) return;
4297
4298            // 9. Consider DropBox entries
4299            // TODO: Implement
4300
4301            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4302            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4303                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4304                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4305                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4306                return;
4307            }
4308        } else {
4309            try {
4310                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4311            } catch (InstallerException ignored) {
4312            }
4313            if (file.getUsableSpace() >= bytes) return;
4314        }
4315
4316        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4317    }
4318
4319    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4320            throws IOException {
4321        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4322        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4323
4324        List<VersionedPackage> packagesToDelete = null;
4325        final long now = System.currentTimeMillis();
4326
4327        synchronized (mPackages) {
4328            final int[] allUsers = sUserManager.getUserIds();
4329            final int libCount = mSharedLibraries.size();
4330            for (int i = 0; i < libCount; i++) {
4331                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4332                if (versionedLib == null) {
4333                    continue;
4334                }
4335                final int versionCount = versionedLib.size();
4336                for (int j = 0; j < versionCount; j++) {
4337                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4338                    // Skip packages that are not static shared libs.
4339                    if (!libInfo.isStatic()) {
4340                        break;
4341                    }
4342                    // Important: We skip static shared libs used for some user since
4343                    // in such a case we need to keep the APK on the device. The check for
4344                    // a lib being used for any user is performed by the uninstall call.
4345                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4346                    // Resolve the package name - we use synthetic package names internally
4347                    final String internalPackageName = resolveInternalPackageNameLPr(
4348                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4349                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4350                    // Skip unused static shared libs cached less than the min period
4351                    // to prevent pruning a lib needed by a subsequently installed package.
4352                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4353                        continue;
4354                    }
4355                    if (packagesToDelete == null) {
4356                        packagesToDelete = new ArrayList<>();
4357                    }
4358                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4359                            declaringPackage.getVersionCode()));
4360                }
4361            }
4362        }
4363
4364        if (packagesToDelete != null) {
4365            final int packageCount = packagesToDelete.size();
4366            for (int i = 0; i < packageCount; i++) {
4367                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4368                // Delete the package synchronously (will fail of the lib used for any user).
4369                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4370                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4371                                == PackageManager.DELETE_SUCCEEDED) {
4372                    if (volume.getUsableSpace() >= neededSpace) {
4373                        return true;
4374                    }
4375                }
4376            }
4377        }
4378
4379        return false;
4380    }
4381
4382    /**
4383     * Update given flags based on encryption status of current user.
4384     */
4385    private int updateFlags(int flags, int userId) {
4386        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4387                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4388            // Caller expressed an explicit opinion about what encryption
4389            // aware/unaware components they want to see, so fall through and
4390            // give them what they want
4391        } else {
4392            // Caller expressed no opinion, so match based on user state
4393            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4394                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4395            } else {
4396                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4397            }
4398        }
4399        return flags;
4400    }
4401
4402    private UserManagerInternal getUserManagerInternal() {
4403        if (mUserManagerInternal == null) {
4404            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4405        }
4406        return mUserManagerInternal;
4407    }
4408
4409    private DeviceIdleController.LocalService getDeviceIdleController() {
4410        if (mDeviceIdleController == null) {
4411            mDeviceIdleController =
4412                    LocalServices.getService(DeviceIdleController.LocalService.class);
4413        }
4414        return mDeviceIdleController;
4415    }
4416
4417    /**
4418     * Update given flags when being used to request {@link PackageInfo}.
4419     */
4420    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4421        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4422        boolean triaged = true;
4423        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4424                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4425            // Caller is asking for component details, so they'd better be
4426            // asking for specific encryption matching behavior, or be triaged
4427            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4428                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4429                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4430                triaged = false;
4431            }
4432        }
4433        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4434                | PackageManager.MATCH_SYSTEM_ONLY
4435                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4436            triaged = false;
4437        }
4438        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4439            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4440                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4441                    + Debug.getCallers(5));
4442        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4443                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4444            // If the caller wants all packages and has a restricted profile associated with it,
4445            // then match all users. This is to make sure that launchers that need to access work
4446            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4447            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4448            flags |= PackageManager.MATCH_ANY_USER;
4449        }
4450        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4451            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4452                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4453        }
4454        return updateFlags(flags, userId);
4455    }
4456
4457    /**
4458     * Update given flags when being used to request {@link ApplicationInfo}.
4459     */
4460    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4461        return updateFlagsForPackage(flags, userId, cookie);
4462    }
4463
4464    /**
4465     * Update given flags when being used to request {@link ComponentInfo}.
4466     */
4467    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4468        if (cookie instanceof Intent) {
4469            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4470                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4471            }
4472        }
4473
4474        boolean triaged = true;
4475        // Caller is asking for component details, so they'd better be
4476        // asking for specific encryption matching behavior, or be triaged
4477        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4478                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4479                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4480            triaged = false;
4481        }
4482        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4483            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4484                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4485        }
4486
4487        return updateFlags(flags, userId);
4488    }
4489
4490    /**
4491     * Update given intent when being used to request {@link ResolveInfo}.
4492     */
4493    private Intent updateIntentForResolve(Intent intent) {
4494        if (intent.getSelector() != null) {
4495            intent = intent.getSelector();
4496        }
4497        if (DEBUG_PREFERRED) {
4498            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4499        }
4500        return intent;
4501    }
4502
4503    /**
4504     * Update given flags when being used to request {@link ResolveInfo}.
4505     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4506     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4507     * flag set. However, this flag is only honoured in three circumstances:
4508     * <ul>
4509     * <li>when called from a system process</li>
4510     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4511     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4512     * action and a {@code android.intent.category.BROWSABLE} category</li>
4513     * </ul>
4514     */
4515    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4516        return updateFlagsForResolve(flags, userId, intent, callingUid,
4517                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4518    }
4519    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4520            boolean wantInstantApps) {
4521        return updateFlagsForResolve(flags, userId, intent, callingUid,
4522                wantInstantApps, false /*onlyExposedExplicitly*/);
4523    }
4524    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4525            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4526        // Safe mode means we shouldn't match any third-party components
4527        if (mSafeMode) {
4528            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4529        }
4530        if (getInstantAppPackageName(callingUid) != null) {
4531            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4532            if (onlyExposedExplicitly) {
4533                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4534            }
4535            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4536            flags |= PackageManager.MATCH_INSTANT;
4537        } else {
4538            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4539            final boolean allowMatchInstant =
4540                    (wantInstantApps
4541                            && Intent.ACTION_VIEW.equals(intent.getAction())
4542                            && hasWebURI(intent))
4543                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4544            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4545                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4546            if (!allowMatchInstant) {
4547                flags &= ~PackageManager.MATCH_INSTANT;
4548            }
4549        }
4550        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4551    }
4552
4553    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4554            int userId) {
4555        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4556        if (ret != null) {
4557            rebaseEnabledOverlays(ret.applicationInfo, userId);
4558        }
4559        return ret;
4560    }
4561
4562    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4563            PackageUserState state, int userId) {
4564        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4565        if (ai != null) {
4566            rebaseEnabledOverlays(ai.applicationInfo, userId);
4567        }
4568        return ai;
4569    }
4570
4571    @Override
4572    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4573        if (!sUserManager.exists(userId)) return null;
4574        final int callingUid = Binder.getCallingUid();
4575        flags = updateFlagsForComponent(flags, userId, component);
4576        enforceCrossUserPermission(callingUid, userId,
4577                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4578        synchronized (mPackages) {
4579            PackageParser.Activity a = mActivities.mActivities.get(component);
4580
4581            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4582            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4583                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4584                if (ps == null) return null;
4585                if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, userId)) {
4586                    return null;
4587                }
4588                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4589            }
4590            if (mResolveComponentName.equals(component)) {
4591                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4592                        userId);
4593            }
4594        }
4595        return null;
4596    }
4597
4598    @Override
4599    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4600            String resolvedType) {
4601        synchronized (mPackages) {
4602            if (component.equals(mResolveComponentName)) {
4603                // The resolver supports EVERYTHING!
4604                return true;
4605            }
4606            final int callingUid = Binder.getCallingUid();
4607            final int callingUserId = UserHandle.getUserId(callingUid);
4608            PackageParser.Activity a = mActivities.mActivities.get(component);
4609            if (a == null) {
4610                return false;
4611            }
4612            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4613            if (ps == null) {
4614                return false;
4615            }
4616            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4617                return false;
4618            }
4619            for (int i=0; i<a.intents.size(); i++) {
4620                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4621                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4622                    return true;
4623                }
4624            }
4625            return false;
4626        }
4627    }
4628
4629    @Override
4630    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4631        if (!sUserManager.exists(userId)) return null;
4632        final int callingUid = Binder.getCallingUid();
4633        flags = updateFlagsForComponent(flags, userId, component);
4634        enforceCrossUserPermission(callingUid, userId,
4635                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4636        synchronized (mPackages) {
4637            PackageParser.Activity a = mReceivers.mActivities.get(component);
4638            if (DEBUG_PACKAGE_INFO) Log.v(
4639                TAG, "getReceiverInfo " + component + ": " + a);
4640            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4641                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4642                if (ps == null) return null;
4643                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4644                    return null;
4645                }
4646                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4647            }
4648        }
4649        return null;
4650    }
4651
4652    @Override
4653    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4654            int flags, int userId) {
4655        if (!sUserManager.exists(userId)) return null;
4656        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4657        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4658            return null;
4659        }
4660
4661        flags = updateFlagsForPackage(flags, userId, null);
4662
4663        final boolean canSeeStaticLibraries =
4664                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4665                        == PERMISSION_GRANTED
4666                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4667                        == PERMISSION_GRANTED
4668                || canRequestPackageInstallsInternal(packageName,
4669                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4670                        false  /* throwIfPermNotDeclared*/)
4671                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4672                        == PERMISSION_GRANTED;
4673
4674        synchronized (mPackages) {
4675            List<SharedLibraryInfo> result = null;
4676
4677            final int libCount = mSharedLibraries.size();
4678            for (int i = 0; i < libCount; i++) {
4679                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4680                if (versionedLib == null) {
4681                    continue;
4682                }
4683
4684                final int versionCount = versionedLib.size();
4685                for (int j = 0; j < versionCount; j++) {
4686                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4687                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4688                        break;
4689                    }
4690                    final long identity = Binder.clearCallingIdentity();
4691                    try {
4692                        PackageInfo packageInfo = getPackageInfoVersioned(
4693                                libInfo.getDeclaringPackage(), flags
4694                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4695                        if (packageInfo == null) {
4696                            continue;
4697                        }
4698                    } finally {
4699                        Binder.restoreCallingIdentity(identity);
4700                    }
4701
4702                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4703                            libInfo.getVersion(), libInfo.getType(),
4704                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4705                            flags, userId));
4706
4707                    if (result == null) {
4708                        result = new ArrayList<>();
4709                    }
4710                    result.add(resLibInfo);
4711                }
4712            }
4713
4714            return result != null ? new ParceledListSlice<>(result) : null;
4715        }
4716    }
4717
4718    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4719            SharedLibraryInfo libInfo, int flags, int userId) {
4720        List<VersionedPackage> versionedPackages = null;
4721        final int packageCount = mSettings.mPackages.size();
4722        for (int i = 0; i < packageCount; i++) {
4723            PackageSetting ps = mSettings.mPackages.valueAt(i);
4724
4725            if (ps == null) {
4726                continue;
4727            }
4728
4729            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4730                continue;
4731            }
4732
4733            final String libName = libInfo.getName();
4734            if (libInfo.isStatic()) {
4735                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4736                if (libIdx < 0) {
4737                    continue;
4738                }
4739                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4740                    continue;
4741                }
4742                if (versionedPackages == null) {
4743                    versionedPackages = new ArrayList<>();
4744                }
4745                // If the dependent is a static shared lib, use the public package name
4746                String dependentPackageName = ps.name;
4747                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4748                    dependentPackageName = ps.pkg.manifestPackageName;
4749                }
4750                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4751            } else if (ps.pkg != null) {
4752                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4753                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4754                    if (versionedPackages == null) {
4755                        versionedPackages = new ArrayList<>();
4756                    }
4757                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4758                }
4759            }
4760        }
4761
4762        return versionedPackages;
4763    }
4764
4765    @Override
4766    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4767        if (!sUserManager.exists(userId)) return null;
4768        final int callingUid = Binder.getCallingUid();
4769        flags = updateFlagsForComponent(flags, userId, component);
4770        enforceCrossUserPermission(callingUid, userId,
4771                false /* requireFullPermission */, false /* checkShell */, "get service info");
4772        synchronized (mPackages) {
4773            PackageParser.Service s = mServices.mServices.get(component);
4774            if (DEBUG_PACKAGE_INFO) Log.v(
4775                TAG, "getServiceInfo " + component + ": " + s);
4776            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4777                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4778                if (ps == null) return null;
4779                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4780                    return null;
4781                }
4782                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4783                        ps.readUserState(userId), userId);
4784                if (si != null) {
4785                    rebaseEnabledOverlays(si.applicationInfo, userId);
4786                }
4787                return si;
4788            }
4789        }
4790        return null;
4791    }
4792
4793    @Override
4794    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4795        if (!sUserManager.exists(userId)) return null;
4796        final int callingUid = Binder.getCallingUid();
4797        flags = updateFlagsForComponent(flags, userId, component);
4798        enforceCrossUserPermission(callingUid, userId,
4799                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4800        synchronized (mPackages) {
4801            PackageParser.Provider p = mProviders.mProviders.get(component);
4802            if (DEBUG_PACKAGE_INFO) Log.v(
4803                TAG, "getProviderInfo " + component + ": " + p);
4804            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4805                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4806                if (ps == null) return null;
4807                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4808                    return null;
4809                }
4810                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4811                        ps.readUserState(userId), userId);
4812                if (pi != null) {
4813                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4814                }
4815                return pi;
4816            }
4817        }
4818        return null;
4819    }
4820
4821    @Override
4822    public String[] getSystemSharedLibraryNames() {
4823        // allow instant applications
4824        synchronized (mPackages) {
4825            Set<String> libs = null;
4826            final int libCount = mSharedLibraries.size();
4827            for (int i = 0; i < libCount; i++) {
4828                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4829                if (versionedLib == null) {
4830                    continue;
4831                }
4832                final int versionCount = versionedLib.size();
4833                for (int j = 0; j < versionCount; j++) {
4834                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4835                    if (!libEntry.info.isStatic()) {
4836                        if (libs == null) {
4837                            libs = new ArraySet<>();
4838                        }
4839                        libs.add(libEntry.info.getName());
4840                        break;
4841                    }
4842                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4843                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4844                            UserHandle.getUserId(Binder.getCallingUid()),
4845                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4846                        if (libs == null) {
4847                            libs = new ArraySet<>();
4848                        }
4849                        libs.add(libEntry.info.getName());
4850                        break;
4851                    }
4852                }
4853            }
4854
4855            if (libs != null) {
4856                String[] libsArray = new String[libs.size()];
4857                libs.toArray(libsArray);
4858                return libsArray;
4859            }
4860
4861            return null;
4862        }
4863    }
4864
4865    @Override
4866    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4867        // allow instant applications
4868        synchronized (mPackages) {
4869            return mServicesSystemSharedLibraryPackageName;
4870        }
4871    }
4872
4873    @Override
4874    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4875        // allow instant applications
4876        synchronized (mPackages) {
4877            return mSharedSystemSharedLibraryPackageName;
4878        }
4879    }
4880
4881    private void updateSequenceNumberLP(String packageName, int[] userList) {
4882        for (int i = userList.length - 1; i >= 0; --i) {
4883            final int userId = userList[i];
4884            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4885            if (changedPackages == null) {
4886                changedPackages = new SparseArray<>();
4887                mChangedPackages.put(userId, changedPackages);
4888            }
4889            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4890            if (sequenceNumbers == null) {
4891                sequenceNumbers = new HashMap<>();
4892                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4893            }
4894            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4895            if (sequenceNumber != null) {
4896                changedPackages.remove(sequenceNumber);
4897            }
4898            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4899            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4900        }
4901        mChangedPackagesSequenceNumber++;
4902    }
4903
4904    @Override
4905    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4906        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4907            return null;
4908        }
4909        synchronized (mPackages) {
4910            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4911                return null;
4912            }
4913            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4914            if (changedPackages == null) {
4915                return null;
4916            }
4917            final List<String> packageNames =
4918                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4919            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4920                final String packageName = changedPackages.get(i);
4921                if (packageName != null) {
4922                    packageNames.add(packageName);
4923                }
4924            }
4925            return packageNames.isEmpty()
4926                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4927        }
4928    }
4929
4930    @Override
4931    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4932        // allow instant applications
4933        ArrayList<FeatureInfo> res;
4934        synchronized (mAvailableFeatures) {
4935            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4936            res.addAll(mAvailableFeatures.values());
4937        }
4938        final FeatureInfo fi = new FeatureInfo();
4939        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4940                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4941        res.add(fi);
4942
4943        return new ParceledListSlice<>(res);
4944    }
4945
4946    @Override
4947    public boolean hasSystemFeature(String name, int version) {
4948        // allow instant applications
4949        synchronized (mAvailableFeatures) {
4950            final FeatureInfo feat = mAvailableFeatures.get(name);
4951            if (feat == null) {
4952                return false;
4953            } else {
4954                return feat.version >= version;
4955            }
4956        }
4957    }
4958
4959    @Override
4960    public int checkPermission(String permName, String pkgName, int userId) {
4961        if (!sUserManager.exists(userId)) {
4962            return PackageManager.PERMISSION_DENIED;
4963        }
4964        final int callingUid = Binder.getCallingUid();
4965
4966        synchronized (mPackages) {
4967            final PackageParser.Package p = mPackages.get(pkgName);
4968            if (p != null && p.mExtras != null) {
4969                final PackageSetting ps = (PackageSetting) p.mExtras;
4970                if (filterAppAccessLPr(ps, callingUid, userId)) {
4971                    return PackageManager.PERMISSION_DENIED;
4972                }
4973                final boolean instantApp = ps.getInstantApp(userId);
4974                final PermissionsState permissionsState = ps.getPermissionsState();
4975                if (permissionsState.hasPermission(permName, userId)) {
4976                    if (instantApp) {
4977                        BasePermission bp = mSettings.mPermissions.get(permName);
4978                        if (bp != null && bp.isInstant()) {
4979                            return PackageManager.PERMISSION_GRANTED;
4980                        }
4981                    } else {
4982                        return PackageManager.PERMISSION_GRANTED;
4983                    }
4984                }
4985                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4986                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4987                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4988                    return PackageManager.PERMISSION_GRANTED;
4989                }
4990            }
4991        }
4992
4993        return PackageManager.PERMISSION_DENIED;
4994    }
4995
4996    @Override
4997    public int checkUidPermission(String permName, int uid) {
4998        final int callingUid = Binder.getCallingUid();
4999        final int callingUserId = UserHandle.getUserId(callingUid);
5000        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5001        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5002        final int userId = UserHandle.getUserId(uid);
5003        if (!sUserManager.exists(userId)) {
5004            return PackageManager.PERMISSION_DENIED;
5005        }
5006
5007        synchronized (mPackages) {
5008            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5009            if (obj != null) {
5010                if (obj instanceof SharedUserSetting) {
5011                    if (isCallerInstantApp) {
5012                        return PackageManager.PERMISSION_DENIED;
5013                    }
5014                } else if (obj instanceof PackageSetting) {
5015                    final PackageSetting ps = (PackageSetting) obj;
5016                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5017                        return PackageManager.PERMISSION_DENIED;
5018                    }
5019                }
5020                final SettingBase settingBase = (SettingBase) obj;
5021                final PermissionsState permissionsState = settingBase.getPermissionsState();
5022                if (permissionsState.hasPermission(permName, userId)) {
5023                    if (isUidInstantApp) {
5024                        BasePermission bp = mSettings.mPermissions.get(permName);
5025                        if (bp != null && bp.isInstant()) {
5026                            return PackageManager.PERMISSION_GRANTED;
5027                        }
5028                    } else {
5029                        return PackageManager.PERMISSION_GRANTED;
5030                    }
5031                }
5032                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5033                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5034                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5035                    return PackageManager.PERMISSION_GRANTED;
5036                }
5037            } else {
5038                ArraySet<String> perms = mSystemPermissions.get(uid);
5039                if (perms != null) {
5040                    if (perms.contains(permName)) {
5041                        return PackageManager.PERMISSION_GRANTED;
5042                    }
5043                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5044                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5045                        return PackageManager.PERMISSION_GRANTED;
5046                    }
5047                }
5048            }
5049        }
5050
5051        return PackageManager.PERMISSION_DENIED;
5052    }
5053
5054    @Override
5055    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5056        if (UserHandle.getCallingUserId() != userId) {
5057            mContext.enforceCallingPermission(
5058                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5059                    "isPermissionRevokedByPolicy for user " + userId);
5060        }
5061
5062        if (checkPermission(permission, packageName, userId)
5063                == PackageManager.PERMISSION_GRANTED) {
5064            return false;
5065        }
5066
5067        final int callingUid = Binder.getCallingUid();
5068        if (getInstantAppPackageName(callingUid) != null) {
5069            if (!isCallerSameApp(packageName, callingUid)) {
5070                return false;
5071            }
5072        } else {
5073            if (isInstantApp(packageName, userId)) {
5074                return false;
5075            }
5076        }
5077
5078        final long identity = Binder.clearCallingIdentity();
5079        try {
5080            final int flags = getPermissionFlags(permission, packageName, userId);
5081            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5082        } finally {
5083            Binder.restoreCallingIdentity(identity);
5084        }
5085    }
5086
5087    @Override
5088    public String getPermissionControllerPackageName() {
5089        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5090            throw new SecurityException("Instant applications don't have access to this method");
5091        }
5092        synchronized (mPackages) {
5093            return mRequiredInstallerPackage;
5094        }
5095    }
5096
5097    /**
5098     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5099     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5100     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5101     * @param message the message to log on security exception
5102     */
5103    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5104            boolean checkShell, String message) {
5105        if (userId < 0) {
5106            throw new IllegalArgumentException("Invalid userId " + userId);
5107        }
5108        if (checkShell) {
5109            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5110        }
5111        if (userId == UserHandle.getUserId(callingUid)) return;
5112        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5113            if (requireFullPermission) {
5114                mContext.enforceCallingOrSelfPermission(
5115                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5116            } else {
5117                try {
5118                    mContext.enforceCallingOrSelfPermission(
5119                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5120                } catch (SecurityException se) {
5121                    mContext.enforceCallingOrSelfPermission(
5122                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5123                }
5124            }
5125        }
5126    }
5127
5128    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5129        if (callingUid == Process.SHELL_UID) {
5130            if (userHandle >= 0
5131                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5132                throw new SecurityException("Shell does not have permission to access user "
5133                        + userHandle);
5134            } else if (userHandle < 0) {
5135                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5136                        + Debug.getCallers(3));
5137            }
5138        }
5139    }
5140
5141    private BasePermission findPermissionTreeLP(String permName) {
5142        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5143            if (permName.startsWith(bp.name) &&
5144                    permName.length() > bp.name.length() &&
5145                    permName.charAt(bp.name.length()) == '.') {
5146                return bp;
5147            }
5148        }
5149        return null;
5150    }
5151
5152    private BasePermission checkPermissionTreeLP(String permName) {
5153        if (permName != null) {
5154            BasePermission bp = findPermissionTreeLP(permName);
5155            if (bp != null) {
5156                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5157                    return bp;
5158                }
5159                throw new SecurityException("Calling uid "
5160                        + Binder.getCallingUid()
5161                        + " is not allowed to add to permission tree "
5162                        + bp.name + " owned by uid " + bp.uid);
5163            }
5164        }
5165        throw new SecurityException("No permission tree found for " + permName);
5166    }
5167
5168    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5169        if (s1 == null) {
5170            return s2 == null;
5171        }
5172        if (s2 == null) {
5173            return false;
5174        }
5175        if (s1.getClass() != s2.getClass()) {
5176            return false;
5177        }
5178        return s1.equals(s2);
5179    }
5180
5181    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5182        if (pi1.icon != pi2.icon) return false;
5183        if (pi1.logo != pi2.logo) return false;
5184        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5185        if (!compareStrings(pi1.name, pi2.name)) return false;
5186        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5187        // We'll take care of setting this one.
5188        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5189        // These are not currently stored in settings.
5190        //if (!compareStrings(pi1.group, pi2.group)) return false;
5191        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5192        //if (pi1.labelRes != pi2.labelRes) return false;
5193        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5194        return true;
5195    }
5196
5197    int permissionInfoFootprint(PermissionInfo info) {
5198        int size = info.name.length();
5199        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5200        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5201        return size;
5202    }
5203
5204    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5205        int size = 0;
5206        for (BasePermission perm : mSettings.mPermissions.values()) {
5207            if (perm.uid == tree.uid) {
5208                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5209            }
5210        }
5211        return size;
5212    }
5213
5214    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5215        // We calculate the max size of permissions defined by this uid and throw
5216        // if that plus the size of 'info' would exceed our stated maximum.
5217        if (tree.uid != Process.SYSTEM_UID) {
5218            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5219            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5220                throw new SecurityException("Permission tree size cap exceeded");
5221            }
5222        }
5223    }
5224
5225    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5226        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5227            throw new SecurityException("Instant apps can't add permissions");
5228        }
5229        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5230            throw new SecurityException("Label must be specified in permission");
5231        }
5232        BasePermission tree = checkPermissionTreeLP(info.name);
5233        BasePermission bp = mSettings.mPermissions.get(info.name);
5234        boolean added = bp == null;
5235        boolean changed = true;
5236        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5237        if (added) {
5238            enforcePermissionCapLocked(info, tree);
5239            bp = new BasePermission(info.name, tree.sourcePackage,
5240                    BasePermission.TYPE_DYNAMIC);
5241        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5242            throw new SecurityException(
5243                    "Not allowed to modify non-dynamic permission "
5244                    + info.name);
5245        } else {
5246            if (bp.protectionLevel == fixedLevel
5247                    && bp.perm.owner.equals(tree.perm.owner)
5248                    && bp.uid == tree.uid
5249                    && comparePermissionInfos(bp.perm.info, info)) {
5250                changed = false;
5251            }
5252        }
5253        bp.protectionLevel = fixedLevel;
5254        info = new PermissionInfo(info);
5255        info.protectionLevel = fixedLevel;
5256        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5257        bp.perm.info.packageName = tree.perm.info.packageName;
5258        bp.uid = tree.uid;
5259        if (added) {
5260            mSettings.mPermissions.put(info.name, bp);
5261        }
5262        if (changed) {
5263            if (!async) {
5264                mSettings.writeLPr();
5265            } else {
5266                scheduleWriteSettingsLocked();
5267            }
5268        }
5269        return added;
5270    }
5271
5272    @Override
5273    public boolean addPermission(PermissionInfo info) {
5274        synchronized (mPackages) {
5275            return addPermissionLocked(info, false);
5276        }
5277    }
5278
5279    @Override
5280    public boolean addPermissionAsync(PermissionInfo info) {
5281        synchronized (mPackages) {
5282            return addPermissionLocked(info, true);
5283        }
5284    }
5285
5286    @Override
5287    public void removePermission(String name) {
5288        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5289            throw new SecurityException("Instant applications don't have access to this method");
5290        }
5291        synchronized (mPackages) {
5292            checkPermissionTreeLP(name);
5293            BasePermission bp = mSettings.mPermissions.get(name);
5294            if (bp != null) {
5295                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5296                    throw new SecurityException(
5297                            "Not allowed to modify non-dynamic permission "
5298                            + name);
5299                }
5300                mSettings.mPermissions.remove(name);
5301                mSettings.writeLPr();
5302            }
5303        }
5304    }
5305
5306    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5307            PackageParser.Package pkg, BasePermission bp) {
5308        int index = pkg.requestedPermissions.indexOf(bp.name);
5309        if (index == -1) {
5310            throw new SecurityException("Package " + pkg.packageName
5311                    + " has not requested permission " + bp.name);
5312        }
5313        if (!bp.isRuntime() && !bp.isDevelopment()) {
5314            throw new SecurityException("Permission " + bp.name
5315                    + " is not a changeable permission type");
5316        }
5317    }
5318
5319    @Override
5320    public void grantRuntimePermission(String packageName, String name, final int userId) {
5321        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5322    }
5323
5324    private void grantRuntimePermission(String packageName, String name, final int userId,
5325            boolean overridePolicy) {
5326        if (!sUserManager.exists(userId)) {
5327            Log.e(TAG, "No such user:" + userId);
5328            return;
5329        }
5330        final int callingUid = Binder.getCallingUid();
5331
5332        mContext.enforceCallingOrSelfPermission(
5333                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5334                "grantRuntimePermission");
5335
5336        enforceCrossUserPermission(callingUid, userId,
5337                true /* requireFullPermission */, true /* checkShell */,
5338                "grantRuntimePermission");
5339
5340        final int uid;
5341        final SettingBase sb;
5342
5343        synchronized (mPackages) {
5344            final PackageParser.Package pkg = mPackages.get(packageName);
5345            if (pkg == null) {
5346                throw new IllegalArgumentException("Unknown package: " + packageName);
5347            }
5348            final BasePermission bp = mSettings.mPermissions.get(name);
5349            if (bp == null) {
5350                throw new IllegalArgumentException("Unknown permission: " + name);
5351            }
5352            sb = (SettingBase) pkg.mExtras;
5353            if (sb == null) {
5354                throw new IllegalArgumentException("Unknown package: " + packageName);
5355            }
5356            if (sb instanceof PackageSetting
5357                    && filterAppAccessLPr((PackageSetting) sb, callingUid, userId)) {
5358                throw new IllegalArgumentException("Unknown package: " + packageName);
5359            }
5360
5361            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5362
5363            // If a permission review is required for legacy apps we represent
5364            // their permissions as always granted runtime ones since we need
5365            // to keep the review required permission flag per user while an
5366            // install permission's state is shared across all users.
5367            if (mPermissionReviewRequired
5368                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5369                    && bp.isRuntime()) {
5370                return;
5371            }
5372
5373            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5374
5375            final PermissionsState permissionsState = sb.getPermissionsState();
5376
5377            final int flags = permissionsState.getPermissionFlags(name, userId);
5378            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5379                throw new SecurityException("Cannot grant system fixed permission "
5380                        + name + " for package " + packageName);
5381            }
5382            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5383                throw new SecurityException("Cannot grant policy fixed permission "
5384                        + name + " for package " + packageName);
5385            }
5386
5387            if (bp.isDevelopment()) {
5388                // Development permissions must be handled specially, since they are not
5389                // normal runtime permissions.  For now they apply to all users.
5390                if (permissionsState.grantInstallPermission(bp) !=
5391                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5392                    scheduleWriteSettingsLocked();
5393                }
5394                return;
5395            }
5396
5397            final PackageSetting ps = mSettings.mPackages.get(packageName);
5398            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5399                throw new SecurityException("Cannot grant non-ephemeral permission"
5400                        + name + " for package " + packageName);
5401            }
5402
5403            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5404                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5405                return;
5406            }
5407
5408            final int result = permissionsState.grantRuntimePermission(bp, userId);
5409            switch (result) {
5410                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5411                    return;
5412                }
5413
5414                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5415                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5416                    mHandler.post(new Runnable() {
5417                        @Override
5418                        public void run() {
5419                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5420                        }
5421                    });
5422                }
5423                break;
5424            }
5425
5426            if (bp.isRuntime()) {
5427                logPermissionGranted(mContext, name, packageName);
5428            }
5429
5430            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5431
5432            // Not critical if that is lost - app has to request again.
5433            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5434        }
5435
5436        // Only need to do this if user is initialized. Otherwise it's a new user
5437        // and there are no processes running as the user yet and there's no need
5438        // to make an expensive call to remount processes for the changed permissions.
5439        if (READ_EXTERNAL_STORAGE.equals(name)
5440                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5441            final long token = Binder.clearCallingIdentity();
5442            try {
5443                if (sUserManager.isInitialized(userId)) {
5444                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5445                            StorageManagerInternal.class);
5446                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5447                }
5448            } finally {
5449                Binder.restoreCallingIdentity(token);
5450            }
5451        }
5452    }
5453
5454    @Override
5455    public void revokeRuntimePermission(String packageName, String name, int userId) {
5456        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5457    }
5458
5459    private void revokeRuntimePermission(String packageName, String name, int userId,
5460            boolean overridePolicy) {
5461        if (!sUserManager.exists(userId)) {
5462            Log.e(TAG, "No such user:" + userId);
5463            return;
5464        }
5465
5466        mContext.enforceCallingOrSelfPermission(
5467                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5468                "revokeRuntimePermission");
5469
5470        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5471                true /* requireFullPermission */, true /* checkShell */,
5472                "revokeRuntimePermission");
5473
5474        final int appId;
5475
5476        synchronized (mPackages) {
5477            final PackageParser.Package pkg = mPackages.get(packageName);
5478            if (pkg == null) {
5479                throw new IllegalArgumentException("Unknown package: " + packageName);
5480            }
5481
5482            final BasePermission bp = mSettings.mPermissions.get(name);
5483            if (bp == null) {
5484                throw new IllegalArgumentException("Unknown permission: " + name);
5485            }
5486
5487            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5488
5489            // If a permission review is required for legacy apps we represent
5490            // their permissions as always granted runtime ones since we need
5491            // to keep the review required permission flag per user while an
5492            // install permission's state is shared across all users.
5493            if (mPermissionReviewRequired
5494                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5495                    && bp.isRuntime()) {
5496                return;
5497            }
5498
5499            SettingBase sb = (SettingBase) pkg.mExtras;
5500            if (sb == null) {
5501                throw new IllegalArgumentException("Unknown package: " + packageName);
5502            }
5503
5504            final PermissionsState permissionsState = sb.getPermissionsState();
5505
5506            final int flags = permissionsState.getPermissionFlags(name, userId);
5507            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5508                throw new SecurityException("Cannot revoke system fixed permission "
5509                        + name + " for package " + packageName);
5510            }
5511            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5512                throw new SecurityException("Cannot revoke policy fixed permission "
5513                        + name + " for package " + packageName);
5514            }
5515
5516            if (bp.isDevelopment()) {
5517                // Development permissions must be handled specially, since they are not
5518                // normal runtime permissions.  For now they apply to all users.
5519                if (permissionsState.revokeInstallPermission(bp) !=
5520                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5521                    scheduleWriteSettingsLocked();
5522                }
5523                return;
5524            }
5525
5526            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5527                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5528                return;
5529            }
5530
5531            if (bp.isRuntime()) {
5532                logPermissionRevoked(mContext, name, packageName);
5533            }
5534
5535            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5536
5537            // Critical, after this call app should never have the permission.
5538            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5539
5540            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5541        }
5542
5543        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5544    }
5545
5546    /**
5547     * Get the first event id for the permission.
5548     *
5549     * <p>There are four events for each permission: <ul>
5550     *     <li>Request permission: first id + 0</li>
5551     *     <li>Grant permission: first id + 1</li>
5552     *     <li>Request for permission denied: first id + 2</li>
5553     *     <li>Revoke permission: first id + 3</li>
5554     * </ul></p>
5555     *
5556     * @param name name of the permission
5557     *
5558     * @return The first event id for the permission
5559     */
5560    private static int getBaseEventId(@NonNull String name) {
5561        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5562
5563        if (eventIdIndex == -1) {
5564            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5565                    || "user".equals(Build.TYPE)) {
5566                Log.i(TAG, "Unknown permission " + name);
5567
5568                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5569            } else {
5570                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5571                //
5572                // Also update
5573                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5574                // - metrics_constants.proto
5575                throw new IllegalStateException("Unknown permission " + name);
5576            }
5577        }
5578
5579        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5580    }
5581
5582    /**
5583     * Log that a permission was revoked.
5584     *
5585     * @param context Context of the caller
5586     * @param name name of the permission
5587     * @param packageName package permission if for
5588     */
5589    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5590            @NonNull String packageName) {
5591        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5592    }
5593
5594    /**
5595     * Log that a permission request was granted.
5596     *
5597     * @param context Context of the caller
5598     * @param name name of the permission
5599     * @param packageName package permission if for
5600     */
5601    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5602            @NonNull String packageName) {
5603        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5604    }
5605
5606    @Override
5607    public void resetRuntimePermissions() {
5608        mContext.enforceCallingOrSelfPermission(
5609                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5610                "revokeRuntimePermission");
5611
5612        int callingUid = Binder.getCallingUid();
5613        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5614            mContext.enforceCallingOrSelfPermission(
5615                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5616                    "resetRuntimePermissions");
5617        }
5618
5619        synchronized (mPackages) {
5620            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5621            for (int userId : UserManagerService.getInstance().getUserIds()) {
5622                final int packageCount = mPackages.size();
5623                for (int i = 0; i < packageCount; i++) {
5624                    PackageParser.Package pkg = mPackages.valueAt(i);
5625                    if (!(pkg.mExtras instanceof PackageSetting)) {
5626                        continue;
5627                    }
5628                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5629                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5630                }
5631            }
5632        }
5633    }
5634
5635    @Override
5636    public int getPermissionFlags(String name, String packageName, int userId) {
5637        if (!sUserManager.exists(userId)) {
5638            return 0;
5639        }
5640
5641        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5642
5643        final int callingUid = Binder.getCallingUid();
5644        enforceCrossUserPermission(callingUid, userId,
5645                true /* requireFullPermission */, false /* checkShell */,
5646                "getPermissionFlags");
5647
5648        synchronized (mPackages) {
5649            final PackageParser.Package pkg = mPackages.get(packageName);
5650            if (pkg == null) {
5651                return 0;
5652            }
5653            final BasePermission bp = mSettings.mPermissions.get(name);
5654            if (bp == null) {
5655                return 0;
5656            }
5657            final SettingBase sb = (SettingBase) pkg.mExtras;
5658            if (sb == null) {
5659                return 0;
5660            }
5661            if (sb instanceof PackageSetting
5662                    && filterAppAccessLPr((PackageSetting) sb, callingUid, userId)) {
5663                return 0;
5664            }
5665            PermissionsState permissionsState = sb.getPermissionsState();
5666            return permissionsState.getPermissionFlags(name, userId);
5667        }
5668    }
5669
5670    @Override
5671    public void updatePermissionFlags(String name, String packageName, int flagMask,
5672            int flagValues, int userId) {
5673        if (!sUserManager.exists(userId)) {
5674            return;
5675        }
5676
5677        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5678
5679        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5680                true /* requireFullPermission */, true /* checkShell */,
5681                "updatePermissionFlags");
5682
5683        // Only the system can change these flags and nothing else.
5684        if (getCallingUid() != Process.SYSTEM_UID) {
5685            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5686            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5687            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5688            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5689            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5690        }
5691
5692        synchronized (mPackages) {
5693            final PackageParser.Package pkg = mPackages.get(packageName);
5694            if (pkg == null) {
5695                throw new IllegalArgumentException("Unknown package: " + packageName);
5696            }
5697
5698            final BasePermission bp = mSettings.mPermissions.get(name);
5699            if (bp == null) {
5700                throw new IllegalArgumentException("Unknown permission: " + name);
5701            }
5702
5703            SettingBase sb = (SettingBase) pkg.mExtras;
5704            if (sb == null) {
5705                throw new IllegalArgumentException("Unknown package: " + packageName);
5706            }
5707
5708            PermissionsState permissionsState = sb.getPermissionsState();
5709
5710            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5711
5712            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5713                // Install and runtime permissions are stored in different places,
5714                // so figure out what permission changed and persist the change.
5715                if (permissionsState.getInstallPermissionState(name) != null) {
5716                    scheduleWriteSettingsLocked();
5717                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5718                        || hadState) {
5719                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5720                }
5721            }
5722        }
5723    }
5724
5725    /**
5726     * Update the permission flags for all packages and runtime permissions of a user in order
5727     * to allow device or profile owner to remove POLICY_FIXED.
5728     */
5729    @Override
5730    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5731        if (!sUserManager.exists(userId)) {
5732            return;
5733        }
5734
5735        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5736
5737        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5738                true /* requireFullPermission */, true /* checkShell */,
5739                "updatePermissionFlagsForAllApps");
5740
5741        // Only the system can change system fixed flags.
5742        if (getCallingUid() != Process.SYSTEM_UID) {
5743            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5744            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5745        }
5746
5747        synchronized (mPackages) {
5748            boolean changed = false;
5749            final int packageCount = mPackages.size();
5750            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5751                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5752                SettingBase sb = (SettingBase) pkg.mExtras;
5753                if (sb == null) {
5754                    continue;
5755                }
5756                PermissionsState permissionsState = sb.getPermissionsState();
5757                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5758                        userId, flagMask, flagValues);
5759            }
5760            if (changed) {
5761                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5762            }
5763        }
5764    }
5765
5766    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5767        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5768                != PackageManager.PERMISSION_GRANTED
5769            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5770                != PackageManager.PERMISSION_GRANTED) {
5771            throw new SecurityException(message + " requires "
5772                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5773                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5774        }
5775    }
5776
5777    @Override
5778    public boolean shouldShowRequestPermissionRationale(String permissionName,
5779            String packageName, int userId) {
5780        if (UserHandle.getCallingUserId() != userId) {
5781            mContext.enforceCallingPermission(
5782                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5783                    "canShowRequestPermissionRationale for user " + userId);
5784        }
5785
5786        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5787        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5788            return false;
5789        }
5790
5791        if (checkPermission(permissionName, packageName, userId)
5792                == PackageManager.PERMISSION_GRANTED) {
5793            return false;
5794        }
5795
5796        final int flags;
5797
5798        final long identity = Binder.clearCallingIdentity();
5799        try {
5800            flags = getPermissionFlags(permissionName,
5801                    packageName, userId);
5802        } finally {
5803            Binder.restoreCallingIdentity(identity);
5804        }
5805
5806        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5807                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5808                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5809
5810        if ((flags & fixedFlags) != 0) {
5811            return false;
5812        }
5813
5814        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5815    }
5816
5817    @Override
5818    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5819        mContext.enforceCallingOrSelfPermission(
5820                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5821                "addOnPermissionsChangeListener");
5822
5823        synchronized (mPackages) {
5824            mOnPermissionChangeListeners.addListenerLocked(listener);
5825        }
5826    }
5827
5828    @Override
5829    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5830        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5831            throw new SecurityException("Instant applications don't have access to this method");
5832        }
5833        synchronized (mPackages) {
5834            mOnPermissionChangeListeners.removeListenerLocked(listener);
5835        }
5836    }
5837
5838    @Override
5839    public boolean isProtectedBroadcast(String actionName) {
5840        // allow instant applications
5841        synchronized (mPackages) {
5842            if (mProtectedBroadcasts.contains(actionName)) {
5843                return true;
5844            } else if (actionName != null) {
5845                // TODO: remove these terrible hacks
5846                if (actionName.startsWith("android.net.netmon.lingerExpired")
5847                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5848                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5849                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5850                    return true;
5851                }
5852            }
5853        }
5854        return false;
5855    }
5856
5857    @Override
5858    public int checkSignatures(String pkg1, String pkg2) {
5859        synchronized (mPackages) {
5860            final PackageParser.Package p1 = mPackages.get(pkg1);
5861            final PackageParser.Package p2 = mPackages.get(pkg2);
5862            if (p1 == null || p1.mExtras == null
5863                    || p2 == null || p2.mExtras == null) {
5864                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5865            }
5866            final int callingUid = Binder.getCallingUid();
5867            final int callingUserId = UserHandle.getUserId(callingUid);
5868            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5869            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5870            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5871                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5872                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5873            }
5874            return compareSignatures(p1.mSignatures, p2.mSignatures);
5875        }
5876    }
5877
5878    @Override
5879    public int checkUidSignatures(int uid1, int uid2) {
5880        final int callingUid = Binder.getCallingUid();
5881        final int callingUserId = UserHandle.getUserId(callingUid);
5882        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5883        // Map to base uids.
5884        uid1 = UserHandle.getAppId(uid1);
5885        uid2 = UserHandle.getAppId(uid2);
5886        // reader
5887        synchronized (mPackages) {
5888            Signature[] s1;
5889            Signature[] s2;
5890            Object obj = mSettings.getUserIdLPr(uid1);
5891            if (obj != null) {
5892                if (obj instanceof SharedUserSetting) {
5893                    if (isCallerInstantApp) {
5894                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5895                    }
5896                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5897                } else if (obj instanceof PackageSetting) {
5898                    final PackageSetting ps = (PackageSetting) obj;
5899                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5900                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5901                    }
5902                    s1 = ps.signatures.mSignatures;
5903                } else {
5904                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5905                }
5906            } else {
5907                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5908            }
5909            obj = mSettings.getUserIdLPr(uid2);
5910            if (obj != null) {
5911                if (obj instanceof SharedUserSetting) {
5912                    if (isCallerInstantApp) {
5913                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5914                    }
5915                    s2 = ((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                    s2 = ps.signatures.mSignatures;
5922                } else {
5923                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5924                }
5925            } else {
5926                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5927            }
5928            return compareSignatures(s1, s2);
5929        }
5930    }
5931
5932    /**
5933     * This method should typically only be used when granting or revoking
5934     * permissions, since the app may immediately restart after this call.
5935     * <p>
5936     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5937     * guard your work against the app being relaunched.
5938     */
5939    private void killUid(int appId, int userId, String reason) {
5940        final long identity = Binder.clearCallingIdentity();
5941        try {
5942            IActivityManager am = ActivityManager.getService();
5943            if (am != null) {
5944                try {
5945                    am.killUid(appId, userId, reason);
5946                } catch (RemoteException e) {
5947                    /* ignore - same process */
5948                }
5949            }
5950        } finally {
5951            Binder.restoreCallingIdentity(identity);
5952        }
5953    }
5954
5955    /**
5956     * Compares two sets of signatures. Returns:
5957     * <br />
5958     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5959     * <br />
5960     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5961     * <br />
5962     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5963     * <br />
5964     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5965     * <br />
5966     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5967     */
5968    static int compareSignatures(Signature[] s1, Signature[] s2) {
5969        if (s1 == null) {
5970            return s2 == null
5971                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5972                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5973        }
5974
5975        if (s2 == null) {
5976            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5977        }
5978
5979        if (s1.length != s2.length) {
5980            return PackageManager.SIGNATURE_NO_MATCH;
5981        }
5982
5983        // Since both signature sets are of size 1, we can compare without HashSets.
5984        if (s1.length == 1) {
5985            return s1[0].equals(s2[0]) ?
5986                    PackageManager.SIGNATURE_MATCH :
5987                    PackageManager.SIGNATURE_NO_MATCH;
5988        }
5989
5990        ArraySet<Signature> set1 = new ArraySet<Signature>();
5991        for (Signature sig : s1) {
5992            set1.add(sig);
5993        }
5994        ArraySet<Signature> set2 = new ArraySet<Signature>();
5995        for (Signature sig : s2) {
5996            set2.add(sig);
5997        }
5998        // Make sure s2 contains all signatures in s1.
5999        if (set1.equals(set2)) {
6000            return PackageManager.SIGNATURE_MATCH;
6001        }
6002        return PackageManager.SIGNATURE_NO_MATCH;
6003    }
6004
6005    /**
6006     * If the database version for this type of package (internal storage or
6007     * external storage) is less than the version where package signatures
6008     * were updated, return true.
6009     */
6010    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6011        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6012        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6013    }
6014
6015    /**
6016     * Used for backward compatibility to make sure any packages with
6017     * certificate chains get upgraded to the new style. {@code existingSigs}
6018     * will be in the old format (since they were stored on disk from before the
6019     * system upgrade) and {@code scannedSigs} will be in the newer format.
6020     */
6021    private int compareSignaturesCompat(PackageSignatures existingSigs,
6022            PackageParser.Package scannedPkg) {
6023        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6024            return PackageManager.SIGNATURE_NO_MATCH;
6025        }
6026
6027        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6028        for (Signature sig : existingSigs.mSignatures) {
6029            existingSet.add(sig);
6030        }
6031        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6032        for (Signature sig : scannedPkg.mSignatures) {
6033            try {
6034                Signature[] chainSignatures = sig.getChainSignatures();
6035                for (Signature chainSig : chainSignatures) {
6036                    scannedCompatSet.add(chainSig);
6037                }
6038            } catch (CertificateEncodingException e) {
6039                scannedCompatSet.add(sig);
6040            }
6041        }
6042        /*
6043         * Make sure the expanded scanned set contains all signatures in the
6044         * existing one.
6045         */
6046        if (scannedCompatSet.equals(existingSet)) {
6047            // Migrate the old signatures to the new scheme.
6048            existingSigs.assignSignatures(scannedPkg.mSignatures);
6049            // The new KeySets will be re-added later in the scanning process.
6050            synchronized (mPackages) {
6051                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6052            }
6053            return PackageManager.SIGNATURE_MATCH;
6054        }
6055        return PackageManager.SIGNATURE_NO_MATCH;
6056    }
6057
6058    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6059        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6060        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6061    }
6062
6063    private int compareSignaturesRecover(PackageSignatures existingSigs,
6064            PackageParser.Package scannedPkg) {
6065        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6066            return PackageManager.SIGNATURE_NO_MATCH;
6067        }
6068
6069        String msg = null;
6070        try {
6071            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6072                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6073                        + scannedPkg.packageName);
6074                return PackageManager.SIGNATURE_MATCH;
6075            }
6076        } catch (CertificateException e) {
6077            msg = e.getMessage();
6078        }
6079
6080        logCriticalInfo(Log.INFO,
6081                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6082        return PackageManager.SIGNATURE_NO_MATCH;
6083    }
6084
6085    @Override
6086    public List<String> getAllPackages() {
6087        final int callingUid = Binder.getCallingUid();
6088        final int callingUserId = UserHandle.getUserId(callingUid);
6089        synchronized (mPackages) {
6090            if (canViewInstantApps(callingUid, callingUserId)) {
6091                return new ArrayList<String>(mPackages.keySet());
6092            }
6093            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6094            final List<String> result = new ArrayList<>();
6095            if (instantAppPkgName != null) {
6096                // caller is an instant application; filter unexposed applications
6097                for (PackageParser.Package pkg : mPackages.values()) {
6098                    if (!pkg.visibleToInstantApps) {
6099                        continue;
6100                    }
6101                    result.add(pkg.packageName);
6102                }
6103            } else {
6104                // caller is a normal application; filter instant applications
6105                for (PackageParser.Package pkg : mPackages.values()) {
6106                    final PackageSetting ps =
6107                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6108                    if (ps != null
6109                            && ps.getInstantApp(callingUserId)
6110                            && !mInstantAppRegistry.isInstantAccessGranted(
6111                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6112                        continue;
6113                    }
6114                    result.add(pkg.packageName);
6115                }
6116            }
6117            return result;
6118        }
6119    }
6120
6121    @Override
6122    public String[] getPackagesForUid(int uid) {
6123        final int callingUid = Binder.getCallingUid();
6124        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6125        final int userId = UserHandle.getUserId(uid);
6126        uid = UserHandle.getAppId(uid);
6127        // reader
6128        synchronized (mPackages) {
6129            Object obj = mSettings.getUserIdLPr(uid);
6130            if (obj instanceof SharedUserSetting) {
6131                if (isCallerInstantApp) {
6132                    return null;
6133                }
6134                final SharedUserSetting sus = (SharedUserSetting) obj;
6135                final int N = sus.packages.size();
6136                String[] res = new String[N];
6137                final Iterator<PackageSetting> it = sus.packages.iterator();
6138                int i = 0;
6139                while (it.hasNext()) {
6140                    PackageSetting ps = it.next();
6141                    if (ps.getInstalled(userId)) {
6142                        res[i++] = ps.name;
6143                    } else {
6144                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6145                    }
6146                }
6147                return res;
6148            } else if (obj instanceof PackageSetting) {
6149                final PackageSetting ps = (PackageSetting) obj;
6150                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6151                    return new String[]{ps.name};
6152                }
6153            }
6154        }
6155        return null;
6156    }
6157
6158    @Override
6159    public String getNameForUid(int uid) {
6160        final int callingUid = Binder.getCallingUid();
6161        if (getInstantAppPackageName(callingUid) != null) {
6162            return null;
6163        }
6164        synchronized (mPackages) {
6165            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6166            if (obj instanceof SharedUserSetting) {
6167                final SharedUserSetting sus = (SharedUserSetting) obj;
6168                return sus.name + ":" + sus.userId;
6169            } else if (obj instanceof PackageSetting) {
6170                final PackageSetting ps = (PackageSetting) obj;
6171                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6172                    return null;
6173                }
6174                return ps.name;
6175            }
6176        }
6177        return null;
6178    }
6179
6180    @Override
6181    public int getUidForSharedUser(String sharedUserName) {
6182        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6183            return -1;
6184        }
6185        if (sharedUserName == null) {
6186            return -1;
6187        }
6188        // reader
6189        synchronized (mPackages) {
6190            SharedUserSetting suid;
6191            try {
6192                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6193                if (suid != null) {
6194                    return suid.userId;
6195                }
6196            } catch (PackageManagerException ignore) {
6197                // can't happen, but, still need to catch it
6198            }
6199            return -1;
6200        }
6201    }
6202
6203    @Override
6204    public int getFlagsForUid(int uid) {
6205        final int callingUid = Binder.getCallingUid();
6206        if (getInstantAppPackageName(callingUid) != null) {
6207            return 0;
6208        }
6209        synchronized (mPackages) {
6210            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6211            if (obj instanceof SharedUserSetting) {
6212                final SharedUserSetting sus = (SharedUserSetting) obj;
6213                return sus.pkgFlags;
6214            } else if (obj instanceof PackageSetting) {
6215                final PackageSetting ps = (PackageSetting) obj;
6216                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6217                    return 0;
6218                }
6219                return ps.pkgFlags;
6220            }
6221        }
6222        return 0;
6223    }
6224
6225    @Override
6226    public int getPrivateFlagsForUid(int uid) {
6227        final int callingUid = Binder.getCallingUid();
6228        if (getInstantAppPackageName(callingUid) != null) {
6229            return 0;
6230        }
6231        synchronized (mPackages) {
6232            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6233            if (obj instanceof SharedUserSetting) {
6234                final SharedUserSetting sus = (SharedUserSetting) obj;
6235                return sus.pkgPrivateFlags;
6236            } else if (obj instanceof PackageSetting) {
6237                final PackageSetting ps = (PackageSetting) obj;
6238                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6239                    return 0;
6240                }
6241                return ps.pkgPrivateFlags;
6242            }
6243        }
6244        return 0;
6245    }
6246
6247    @Override
6248    public boolean isUidPrivileged(int uid) {
6249        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6250            return false;
6251        }
6252        uid = UserHandle.getAppId(uid);
6253        // reader
6254        synchronized (mPackages) {
6255            Object obj = mSettings.getUserIdLPr(uid);
6256            if (obj instanceof SharedUserSetting) {
6257                final SharedUserSetting sus = (SharedUserSetting) obj;
6258                final Iterator<PackageSetting> it = sus.packages.iterator();
6259                while (it.hasNext()) {
6260                    if (it.next().isPrivileged()) {
6261                        return true;
6262                    }
6263                }
6264            } else if (obj instanceof PackageSetting) {
6265                final PackageSetting ps = (PackageSetting) obj;
6266                return ps.isPrivileged();
6267            }
6268        }
6269        return false;
6270    }
6271
6272    @Override
6273    public String[] getAppOpPermissionPackages(String permissionName) {
6274        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6275            return null;
6276        }
6277        synchronized (mPackages) {
6278            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6279            if (pkgs == null) {
6280                return null;
6281            }
6282            return pkgs.toArray(new String[pkgs.size()]);
6283        }
6284    }
6285
6286    @Override
6287    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6288            int flags, int userId) {
6289        return resolveIntentInternal(
6290                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6291    }
6292
6293    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6294            int flags, int userId, boolean resolveForStart) {
6295        try {
6296            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6297
6298            if (!sUserManager.exists(userId)) return null;
6299            final int callingUid = Binder.getCallingUid();
6300            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6301            enforceCrossUserPermission(callingUid, userId,
6302                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6303
6304            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6305            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6306                    flags, userId, resolveForStart);
6307            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6308
6309            final ResolveInfo bestChoice =
6310                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6311            return bestChoice;
6312        } finally {
6313            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6314        }
6315    }
6316
6317    @Override
6318    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6319        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6320            throw new SecurityException(
6321                    "findPersistentPreferredActivity can only be run by the system");
6322        }
6323        if (!sUserManager.exists(userId)) {
6324            return null;
6325        }
6326        final int callingUid = Binder.getCallingUid();
6327        intent = updateIntentForResolve(intent);
6328        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6329        final int flags = updateFlagsForResolve(
6330                0, userId, intent, callingUid, false /*includeInstantApps*/);
6331        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6332                userId);
6333        synchronized (mPackages) {
6334            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6335                    userId);
6336        }
6337    }
6338
6339    @Override
6340    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6341            IntentFilter filter, int match, ComponentName activity) {
6342        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6343            return;
6344        }
6345        final int userId = UserHandle.getCallingUserId();
6346        if (DEBUG_PREFERRED) {
6347            Log.v(TAG, "setLastChosenActivity intent=" + intent
6348                + " resolvedType=" + resolvedType
6349                + " flags=" + flags
6350                + " filter=" + filter
6351                + " match=" + match
6352                + " activity=" + activity);
6353            filter.dump(new PrintStreamPrinter(System.out), "    ");
6354        }
6355        intent.setComponent(null);
6356        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6357                userId);
6358        // Find any earlier preferred or last chosen entries and nuke them
6359        findPreferredActivity(intent, resolvedType,
6360                flags, query, 0, false, true, false, userId);
6361        // Add the new activity as the last chosen for this filter
6362        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6363                "Setting last chosen");
6364    }
6365
6366    @Override
6367    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6368        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6369            return null;
6370        }
6371        final int userId = UserHandle.getCallingUserId();
6372        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6373        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6374                userId);
6375        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6376                false, false, false, userId);
6377    }
6378
6379    /**
6380     * Returns whether or not instant apps have been disabled remotely.
6381     */
6382    private boolean isEphemeralDisabled() {
6383        return mEphemeralAppsDisabled;
6384    }
6385
6386    private boolean isInstantAppAllowed(
6387            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6388            boolean skipPackageCheck) {
6389        if (mInstantAppResolverConnection == null) {
6390            return false;
6391        }
6392        if (mInstantAppInstallerActivity == null) {
6393            return false;
6394        }
6395        if (intent.getComponent() != null) {
6396            return false;
6397        }
6398        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6399            return false;
6400        }
6401        if (!skipPackageCheck && intent.getPackage() != null) {
6402            return false;
6403        }
6404        final boolean isWebUri = hasWebURI(intent);
6405        if (!isWebUri || intent.getData().getHost() == null) {
6406            return false;
6407        }
6408        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6409        // Or if there's already an ephemeral app installed that handles the action
6410        synchronized (mPackages) {
6411            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6412            for (int n = 0; n < count; n++) {
6413                final ResolveInfo info = resolvedActivities.get(n);
6414                final String packageName = info.activityInfo.packageName;
6415                final PackageSetting ps = mSettings.mPackages.get(packageName);
6416                if (ps != null) {
6417                    // only check domain verification status if the app is not a browser
6418                    if (!info.handleAllWebDataURI) {
6419                        // Try to get the status from User settings first
6420                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6421                        final int status = (int) (packedStatus >> 32);
6422                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6423                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6424                            if (DEBUG_EPHEMERAL) {
6425                                Slog.v(TAG, "DENY instant app;"
6426                                    + " pkg: " + packageName + ", status: " + status);
6427                            }
6428                            return false;
6429                        }
6430                    }
6431                    if (ps.getInstantApp(userId)) {
6432                        if (DEBUG_EPHEMERAL) {
6433                            Slog.v(TAG, "DENY instant app installed;"
6434                                    + " pkg: " + packageName);
6435                        }
6436                        return false;
6437                    }
6438                }
6439            }
6440        }
6441        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6442        return true;
6443    }
6444
6445    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6446            Intent origIntent, String resolvedType, String callingPackage,
6447            Bundle verificationBundle, int userId) {
6448        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6449                new InstantAppRequest(responseObj, origIntent, resolvedType,
6450                        callingPackage, userId, verificationBundle));
6451        mHandler.sendMessage(msg);
6452    }
6453
6454    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6455            int flags, List<ResolveInfo> query, int userId) {
6456        if (query != null) {
6457            final int N = query.size();
6458            if (N == 1) {
6459                return query.get(0);
6460            } else if (N > 1) {
6461                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6462                // If there is more than one activity with the same priority,
6463                // then let the user decide between them.
6464                ResolveInfo r0 = query.get(0);
6465                ResolveInfo r1 = query.get(1);
6466                if (DEBUG_INTENT_MATCHING || debug) {
6467                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6468                            + r1.activityInfo.name + "=" + r1.priority);
6469                }
6470                // If the first activity has a higher priority, or a different
6471                // default, then it is always desirable to pick it.
6472                if (r0.priority != r1.priority
6473                        || r0.preferredOrder != r1.preferredOrder
6474                        || r0.isDefault != r1.isDefault) {
6475                    return query.get(0);
6476                }
6477                // If we have saved a preference for a preferred activity for
6478                // this Intent, use that.
6479                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6480                        flags, query, r0.priority, true, false, debug, userId);
6481                if (ri != null) {
6482                    return ri;
6483                }
6484                // If we have an ephemeral app, use it
6485                for (int i = 0; i < N; i++) {
6486                    ri = query.get(i);
6487                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6488                        final String packageName = ri.activityInfo.packageName;
6489                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6490                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6491                        final int status = (int)(packedStatus >> 32);
6492                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6493                            return ri;
6494                        }
6495                    }
6496                }
6497                ri = new ResolveInfo(mResolveInfo);
6498                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6499                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6500                // If all of the options come from the same package, show the application's
6501                // label and icon instead of the generic resolver's.
6502                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6503                // and then throw away the ResolveInfo itself, meaning that the caller loses
6504                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6505                // a fallback for this case; we only set the target package's resources on
6506                // the ResolveInfo, not the ActivityInfo.
6507                final String intentPackage = intent.getPackage();
6508                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6509                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6510                    ri.resolvePackageName = intentPackage;
6511                    if (userNeedsBadging(userId)) {
6512                        ri.noResourceId = true;
6513                    } else {
6514                        ri.icon = appi.icon;
6515                    }
6516                    ri.iconResourceId = appi.icon;
6517                    ri.labelRes = appi.labelRes;
6518                }
6519                ri.activityInfo.applicationInfo = new ApplicationInfo(
6520                        ri.activityInfo.applicationInfo);
6521                if (userId != 0) {
6522                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6523                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6524                }
6525                // Make sure that the resolver is displayable in car mode
6526                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6527                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6528                return ri;
6529            }
6530        }
6531        return null;
6532    }
6533
6534    /**
6535     * Return true if the given list is not empty and all of its contents have
6536     * an activityInfo with the given package name.
6537     */
6538    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6539        if (ArrayUtils.isEmpty(list)) {
6540            return false;
6541        }
6542        for (int i = 0, N = list.size(); i < N; i++) {
6543            final ResolveInfo ri = list.get(i);
6544            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6545            if (ai == null || !packageName.equals(ai.packageName)) {
6546                return false;
6547            }
6548        }
6549        return true;
6550    }
6551
6552    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6553            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6554        final int N = query.size();
6555        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6556                .get(userId);
6557        // Get the list of persistent preferred activities that handle the intent
6558        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6559        List<PersistentPreferredActivity> pprefs = ppir != null
6560                ? ppir.queryIntent(intent, resolvedType,
6561                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6562                        userId)
6563                : null;
6564        if (pprefs != null && pprefs.size() > 0) {
6565            final int M = pprefs.size();
6566            for (int i=0; i<M; i++) {
6567                final PersistentPreferredActivity ppa = pprefs.get(i);
6568                if (DEBUG_PREFERRED || debug) {
6569                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6570                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6571                            + "\n  component=" + ppa.mComponent);
6572                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6573                }
6574                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6575                        flags | MATCH_DISABLED_COMPONENTS, userId);
6576                if (DEBUG_PREFERRED || debug) {
6577                    Slog.v(TAG, "Found persistent preferred activity:");
6578                    if (ai != null) {
6579                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6580                    } else {
6581                        Slog.v(TAG, "  null");
6582                    }
6583                }
6584                if (ai == null) {
6585                    // This previously registered persistent preferred activity
6586                    // component is no longer known. Ignore it and do NOT remove it.
6587                    continue;
6588                }
6589                for (int j=0; j<N; j++) {
6590                    final ResolveInfo ri = query.get(j);
6591                    if (!ri.activityInfo.applicationInfo.packageName
6592                            .equals(ai.applicationInfo.packageName)) {
6593                        continue;
6594                    }
6595                    if (!ri.activityInfo.name.equals(ai.name)) {
6596                        continue;
6597                    }
6598                    //  Found a persistent preference that can handle the intent.
6599                    if (DEBUG_PREFERRED || debug) {
6600                        Slog.v(TAG, "Returning persistent preferred activity: " +
6601                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6602                    }
6603                    return ri;
6604                }
6605            }
6606        }
6607        return null;
6608    }
6609
6610    // TODO: handle preferred activities missing while user has amnesia
6611    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6612            List<ResolveInfo> query, int priority, boolean always,
6613            boolean removeMatches, boolean debug, int userId) {
6614        if (!sUserManager.exists(userId)) return null;
6615        final int callingUid = Binder.getCallingUid();
6616        flags = updateFlagsForResolve(
6617                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6618        intent = updateIntentForResolve(intent);
6619        // writer
6620        synchronized (mPackages) {
6621            // Try to find a matching persistent preferred activity.
6622            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6623                    debug, userId);
6624
6625            // If a persistent preferred activity matched, use it.
6626            if (pri != null) {
6627                return pri;
6628            }
6629
6630            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6631            // Get the list of preferred activities that handle the intent
6632            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6633            List<PreferredActivity> prefs = pir != null
6634                    ? pir.queryIntent(intent, resolvedType,
6635                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6636                            userId)
6637                    : null;
6638            if (prefs != null && prefs.size() > 0) {
6639                boolean changed = false;
6640                try {
6641                    // First figure out how good the original match set is.
6642                    // We will only allow preferred activities that came
6643                    // from the same match quality.
6644                    int match = 0;
6645
6646                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6647
6648                    final int N = query.size();
6649                    for (int j=0; j<N; j++) {
6650                        final ResolveInfo ri = query.get(j);
6651                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6652                                + ": 0x" + Integer.toHexString(match));
6653                        if (ri.match > match) {
6654                            match = ri.match;
6655                        }
6656                    }
6657
6658                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6659                            + Integer.toHexString(match));
6660
6661                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6662                    final int M = prefs.size();
6663                    for (int i=0; i<M; i++) {
6664                        final PreferredActivity pa = prefs.get(i);
6665                        if (DEBUG_PREFERRED || debug) {
6666                            Slog.v(TAG, "Checking PreferredActivity ds="
6667                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6668                                    + "\n  component=" + pa.mPref.mComponent);
6669                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6670                        }
6671                        if (pa.mPref.mMatch != match) {
6672                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6673                                    + Integer.toHexString(pa.mPref.mMatch));
6674                            continue;
6675                        }
6676                        // If it's not an "always" type preferred activity and that's what we're
6677                        // looking for, skip it.
6678                        if (always && !pa.mPref.mAlways) {
6679                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6680                            continue;
6681                        }
6682                        final ActivityInfo ai = getActivityInfo(
6683                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6684                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6685                                userId);
6686                        if (DEBUG_PREFERRED || debug) {
6687                            Slog.v(TAG, "Found preferred activity:");
6688                            if (ai != null) {
6689                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6690                            } else {
6691                                Slog.v(TAG, "  null");
6692                            }
6693                        }
6694                        if (ai == null) {
6695                            // This previously registered preferred activity
6696                            // component is no longer known.  Most likely an update
6697                            // to the app was installed and in the new version this
6698                            // component no longer exists.  Clean it up by removing
6699                            // it from the preferred activities list, and skip it.
6700                            Slog.w(TAG, "Removing dangling preferred activity: "
6701                                    + pa.mPref.mComponent);
6702                            pir.removeFilter(pa);
6703                            changed = true;
6704                            continue;
6705                        }
6706                        for (int j=0; j<N; j++) {
6707                            final ResolveInfo ri = query.get(j);
6708                            if (!ri.activityInfo.applicationInfo.packageName
6709                                    .equals(ai.applicationInfo.packageName)) {
6710                                continue;
6711                            }
6712                            if (!ri.activityInfo.name.equals(ai.name)) {
6713                                continue;
6714                            }
6715
6716                            if (removeMatches) {
6717                                pir.removeFilter(pa);
6718                                changed = true;
6719                                if (DEBUG_PREFERRED) {
6720                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6721                                }
6722                                break;
6723                            }
6724
6725                            // Okay we found a previously set preferred or last chosen app.
6726                            // If the result set is different from when this
6727                            // was created, we need to clear it and re-ask the
6728                            // user their preference, if we're looking for an "always" type entry.
6729                            if (always && !pa.mPref.sameSet(query)) {
6730                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6731                                        + intent + " type " + resolvedType);
6732                                if (DEBUG_PREFERRED) {
6733                                    Slog.v(TAG, "Removing preferred activity since set changed "
6734                                            + pa.mPref.mComponent);
6735                                }
6736                                pir.removeFilter(pa);
6737                                // Re-add the filter as a "last chosen" entry (!always)
6738                                PreferredActivity lastChosen = new PreferredActivity(
6739                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6740                                pir.addFilter(lastChosen);
6741                                changed = true;
6742                                return null;
6743                            }
6744
6745                            // Yay! Either the set matched or we're looking for the last chosen
6746                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6747                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6748                            return ri;
6749                        }
6750                    }
6751                } finally {
6752                    if (changed) {
6753                        if (DEBUG_PREFERRED) {
6754                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6755                        }
6756                        scheduleWritePackageRestrictionsLocked(userId);
6757                    }
6758                }
6759            }
6760        }
6761        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6762        return null;
6763    }
6764
6765    /*
6766     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6767     */
6768    @Override
6769    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6770            int targetUserId) {
6771        mContext.enforceCallingOrSelfPermission(
6772                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6773        List<CrossProfileIntentFilter> matches =
6774                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6775        if (matches != null) {
6776            int size = matches.size();
6777            for (int i = 0; i < size; i++) {
6778                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6779            }
6780        }
6781        if (hasWebURI(intent)) {
6782            // cross-profile app linking works only towards the parent.
6783            final int callingUid = Binder.getCallingUid();
6784            final UserInfo parent = getProfileParent(sourceUserId);
6785            synchronized(mPackages) {
6786                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6787                        false /*includeInstantApps*/);
6788                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6789                        intent, resolvedType, flags, sourceUserId, parent.id);
6790                return xpDomainInfo != null;
6791            }
6792        }
6793        return false;
6794    }
6795
6796    private UserInfo getProfileParent(int userId) {
6797        final long identity = Binder.clearCallingIdentity();
6798        try {
6799            return sUserManager.getProfileParent(userId);
6800        } finally {
6801            Binder.restoreCallingIdentity(identity);
6802        }
6803    }
6804
6805    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6806            String resolvedType, int userId) {
6807        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6808        if (resolver != null) {
6809            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6810        }
6811        return null;
6812    }
6813
6814    @Override
6815    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6816            String resolvedType, int flags, int userId) {
6817        try {
6818            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6819
6820            return new ParceledListSlice<>(
6821                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6822        } finally {
6823            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6824        }
6825    }
6826
6827    /**
6828     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6829     * instant, returns {@code null}.
6830     */
6831    private String getInstantAppPackageName(int callingUid) {
6832        synchronized (mPackages) {
6833            // If the caller is an isolated app use the owner's uid for the lookup.
6834            if (Process.isIsolated(callingUid)) {
6835                callingUid = mIsolatedOwners.get(callingUid);
6836            }
6837            final int appId = UserHandle.getAppId(callingUid);
6838            final Object obj = mSettings.getUserIdLPr(appId);
6839            if (obj instanceof PackageSetting) {
6840                final PackageSetting ps = (PackageSetting) obj;
6841                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6842                return isInstantApp ? ps.pkg.packageName : null;
6843            }
6844        }
6845        return null;
6846    }
6847
6848    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6849            String resolvedType, int flags, int userId) {
6850        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6851    }
6852
6853    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6854            String resolvedType, int flags, int userId, boolean resolveForStart) {
6855        if (!sUserManager.exists(userId)) return Collections.emptyList();
6856        final int callingUid = Binder.getCallingUid();
6857        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6858        enforceCrossUserPermission(callingUid, userId,
6859                false /* requireFullPermission */, false /* checkShell */,
6860                "query intent activities");
6861        final String pkgName = intent.getPackage();
6862        ComponentName comp = intent.getComponent();
6863        if (comp == null) {
6864            if (intent.getSelector() != null) {
6865                intent = intent.getSelector();
6866                comp = intent.getComponent();
6867            }
6868        }
6869
6870        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
6871                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6872        if (comp != null) {
6873            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6874            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6875            if (ai != null) {
6876                // When specifying an explicit component, we prevent the activity from being
6877                // used when either 1) the calling package is normal and the activity is within
6878                // an ephemeral application or 2) the calling package is ephemeral and the
6879                // activity is not visible to ephemeral applications.
6880                final boolean matchInstantApp =
6881                        (flags & PackageManager.MATCH_INSTANT) != 0;
6882                final boolean matchVisibleToInstantAppOnly =
6883                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6884                final boolean matchExplicitlyVisibleOnly =
6885                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6886                final boolean isCallerInstantApp =
6887                        instantAppPkgName != null;
6888                final boolean isTargetSameInstantApp =
6889                        comp.getPackageName().equals(instantAppPkgName);
6890                final boolean isTargetInstantApp =
6891                        (ai.applicationInfo.privateFlags
6892                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6893                final boolean isTargetVisibleToInstantApp =
6894                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6895                final boolean isTargetExplicitlyVisibleToInstantApp =
6896                        isTargetVisibleToInstantApp
6897                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6898                final boolean isTargetHiddenFromInstantApp =
6899                        !isTargetVisibleToInstantApp
6900                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6901                final boolean blockResolution =
6902                        !isTargetSameInstantApp
6903                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6904                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6905                                        && isTargetHiddenFromInstantApp));
6906                if (!blockResolution) {
6907                    final ResolveInfo ri = new ResolveInfo();
6908                    ri.activityInfo = ai;
6909                    list.add(ri);
6910                }
6911            }
6912            return applyPostResolutionFilter(list, instantAppPkgName);
6913        }
6914
6915        // reader
6916        boolean sortResult = false;
6917        boolean addEphemeral = false;
6918        List<ResolveInfo> result;
6919        final boolean ephemeralDisabled = isEphemeralDisabled();
6920        synchronized (mPackages) {
6921            if (pkgName == null) {
6922                List<CrossProfileIntentFilter> matchingFilters =
6923                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6924                // Check for results that need to skip the current profile.
6925                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6926                        resolvedType, flags, userId);
6927                if (xpResolveInfo != null) {
6928                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6929                    xpResult.add(xpResolveInfo);
6930                    return applyPostResolutionFilter(
6931                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6932                }
6933
6934                // Check for results in the current profile.
6935                result = filterIfNotSystemUser(mActivities.queryIntent(
6936                        intent, resolvedType, flags, userId), userId);
6937                addEphemeral = !ephemeralDisabled
6938                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6939                // Check for cross profile results.
6940                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6941                xpResolveInfo = queryCrossProfileIntents(
6942                        matchingFilters, intent, resolvedType, flags, userId,
6943                        hasNonNegativePriorityResult);
6944                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6945                    boolean isVisibleToUser = filterIfNotSystemUser(
6946                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6947                    if (isVisibleToUser) {
6948                        result.add(xpResolveInfo);
6949                        sortResult = true;
6950                    }
6951                }
6952                if (hasWebURI(intent)) {
6953                    CrossProfileDomainInfo xpDomainInfo = null;
6954                    final UserInfo parent = getProfileParent(userId);
6955                    if (parent != null) {
6956                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6957                                flags, userId, parent.id);
6958                    }
6959                    if (xpDomainInfo != null) {
6960                        if (xpResolveInfo != null) {
6961                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6962                            // in the result.
6963                            result.remove(xpResolveInfo);
6964                        }
6965                        if (result.size() == 0 && !addEphemeral) {
6966                            // No result in current profile, but found candidate in parent user.
6967                            // And we are not going to add emphemeral app, so we can return the
6968                            // result straight away.
6969                            result.add(xpDomainInfo.resolveInfo);
6970                            return applyPostResolutionFilter(result, instantAppPkgName);
6971                        }
6972                    } else if (result.size() <= 1 && !addEphemeral) {
6973                        // No result in parent user and <= 1 result in current profile, and we
6974                        // are not going to add emphemeral app, so we can return the result without
6975                        // further processing.
6976                        return applyPostResolutionFilter(result, instantAppPkgName);
6977                    }
6978                    // We have more than one candidate (combining results from current and parent
6979                    // profile), so we need filtering and sorting.
6980                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6981                            intent, flags, result, xpDomainInfo, userId);
6982                    sortResult = true;
6983                }
6984            } else {
6985                final PackageParser.Package pkg = mPackages.get(pkgName);
6986                result = null;
6987                if (pkg != null) {
6988                    result = filterIfNotSystemUser(
6989                            mActivities.queryIntentForPackage(
6990                                    intent, resolvedType, flags, pkg.activities, userId),
6991                            userId);
6992                }
6993                if (result == null || result.size() == 0) {
6994                    // the caller wants to resolve for a particular package; however, there
6995                    // were no installed results, so, try to find an ephemeral result
6996                    addEphemeral = !ephemeralDisabled
6997                            && isInstantAppAllowed(
6998                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6999                    if (result == null) {
7000                        result = new ArrayList<>();
7001                    }
7002                }
7003            }
7004        }
7005        if (addEphemeral) {
7006            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7007        }
7008        if (sortResult) {
7009            Collections.sort(result, mResolvePrioritySorter);
7010        }
7011        return applyPostResolutionFilter(result, instantAppPkgName);
7012    }
7013
7014    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7015            String resolvedType, int flags, int userId) {
7016        // first, check to see if we've got an instant app already installed
7017        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7018        ResolveInfo localInstantApp = null;
7019        boolean blockResolution = false;
7020        if (!alreadyResolvedLocally) {
7021            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7022                    flags
7023                        | PackageManager.GET_RESOLVED_FILTER
7024                        | PackageManager.MATCH_INSTANT
7025                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7026                    userId);
7027            for (int i = instantApps.size() - 1; i >= 0; --i) {
7028                final ResolveInfo info = instantApps.get(i);
7029                final String packageName = info.activityInfo.packageName;
7030                final PackageSetting ps = mSettings.mPackages.get(packageName);
7031                if (ps.getInstantApp(userId)) {
7032                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7033                    final int status = (int)(packedStatus >> 32);
7034                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7035                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7036                        // there's a local instant application installed, but, the user has
7037                        // chosen to never use it; skip resolution and don't acknowledge
7038                        // an instant application is even available
7039                        if (DEBUG_EPHEMERAL) {
7040                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7041                        }
7042                        blockResolution = true;
7043                        break;
7044                    } else {
7045                        // we have a locally installed instant application; skip resolution
7046                        // but acknowledge there's an instant application available
7047                        if (DEBUG_EPHEMERAL) {
7048                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7049                        }
7050                        localInstantApp = info;
7051                        break;
7052                    }
7053                }
7054            }
7055        }
7056        // no app installed, let's see if one's available
7057        AuxiliaryResolveInfo auxiliaryResponse = null;
7058        if (!blockResolution) {
7059            if (localInstantApp == null) {
7060                // we don't have an instant app locally, resolve externally
7061                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7062                final InstantAppRequest requestObject = new InstantAppRequest(
7063                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7064                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7065                auxiliaryResponse =
7066                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7067                                mContext, mInstantAppResolverConnection, requestObject);
7068                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7069            } else {
7070                // we have an instant application locally, but, we can't admit that since
7071                // callers shouldn't be able to determine prior browsing. create a dummy
7072                // auxiliary response so the downstream code behaves as if there's an
7073                // instant application available externally. when it comes time to start
7074                // the instant application, we'll do the right thing.
7075                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7076                auxiliaryResponse = new AuxiliaryResolveInfo(
7077                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7078            }
7079        }
7080        if (auxiliaryResponse != null) {
7081            if (DEBUG_EPHEMERAL) {
7082                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7083            }
7084            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7085            final PackageSetting ps =
7086                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7087            if (ps != null) {
7088                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7089                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7090                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7091                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7092                // make sure this resolver is the default
7093                ephemeralInstaller.isDefault = true;
7094                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7095                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7096                // add a non-generic filter
7097                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7098                ephemeralInstaller.filter.addDataPath(
7099                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7100                ephemeralInstaller.isInstantAppAvailable = true;
7101                result.add(ephemeralInstaller);
7102            }
7103        }
7104        return result;
7105    }
7106
7107    private static class CrossProfileDomainInfo {
7108        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7109        ResolveInfo resolveInfo;
7110        /* Best domain verification status of the activities found in the other profile */
7111        int bestDomainVerificationStatus;
7112    }
7113
7114    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7115            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7116        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7117                sourceUserId)) {
7118            return null;
7119        }
7120        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7121                resolvedType, flags, parentUserId);
7122
7123        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7124            return null;
7125        }
7126        CrossProfileDomainInfo result = null;
7127        int size = resultTargetUser.size();
7128        for (int i = 0; i < size; i++) {
7129            ResolveInfo riTargetUser = resultTargetUser.get(i);
7130            // Intent filter verification is only for filters that specify a host. So don't return
7131            // those that handle all web uris.
7132            if (riTargetUser.handleAllWebDataURI) {
7133                continue;
7134            }
7135            String packageName = riTargetUser.activityInfo.packageName;
7136            PackageSetting ps = mSettings.mPackages.get(packageName);
7137            if (ps == null) {
7138                continue;
7139            }
7140            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7141            int status = (int)(verificationState >> 32);
7142            if (result == null) {
7143                result = new CrossProfileDomainInfo();
7144                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7145                        sourceUserId, parentUserId);
7146                result.bestDomainVerificationStatus = status;
7147            } else {
7148                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7149                        result.bestDomainVerificationStatus);
7150            }
7151        }
7152        // Don't consider matches with status NEVER across profiles.
7153        if (result != null && result.bestDomainVerificationStatus
7154                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7155            return null;
7156        }
7157        return result;
7158    }
7159
7160    /**
7161     * Verification statuses are ordered from the worse to the best, except for
7162     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7163     */
7164    private int bestDomainVerificationStatus(int status1, int status2) {
7165        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7166            return status2;
7167        }
7168        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7169            return status1;
7170        }
7171        return (int) MathUtils.max(status1, status2);
7172    }
7173
7174    private boolean isUserEnabled(int userId) {
7175        long callingId = Binder.clearCallingIdentity();
7176        try {
7177            UserInfo userInfo = sUserManager.getUserInfo(userId);
7178            return userInfo != null && userInfo.isEnabled();
7179        } finally {
7180            Binder.restoreCallingIdentity(callingId);
7181        }
7182    }
7183
7184    /**
7185     * Filter out activities with systemUserOnly flag set, when current user is not System.
7186     *
7187     * @return filtered list
7188     */
7189    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7190        if (userId == UserHandle.USER_SYSTEM) {
7191            return resolveInfos;
7192        }
7193        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7194            ResolveInfo info = resolveInfos.get(i);
7195            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7196                resolveInfos.remove(i);
7197            }
7198        }
7199        return resolveInfos;
7200    }
7201
7202    /**
7203     * Filters out ephemeral activities.
7204     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7205     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7206     *
7207     * @param resolveInfos The pre-filtered list of resolved activities
7208     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7209     *          is performed.
7210     * @return A filtered list of resolved activities.
7211     */
7212    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7213            String ephemeralPkgName) {
7214        // TODO: When adding on-demand split support for non-instant apps, remove this check
7215        // and always apply post filtering
7216        if (ephemeralPkgName == null) {
7217            return resolveInfos;
7218        }
7219        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7220            final ResolveInfo info = resolveInfos.get(i);
7221            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7222            // allow activities that are defined in the provided package
7223            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7224                if (info.activityInfo.splitName != null
7225                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7226                                info.activityInfo.splitName)) {
7227                    // requested activity is defined in a split that hasn't been installed yet.
7228                    // add the installer to the resolve list
7229                    if (DEBUG_EPHEMERAL) {
7230                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7231                    }
7232                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7233                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7234                            info.activityInfo.packageName, info.activityInfo.splitName,
7235                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7236                    // make sure this resolver is the default
7237                    installerInfo.isDefault = true;
7238                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7239                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7240                    // add a non-generic filter
7241                    installerInfo.filter = new IntentFilter();
7242                    // load resources from the correct package
7243                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7244                    resolveInfos.set(i, installerInfo);
7245                }
7246                continue;
7247            }
7248            // allow activities that have been explicitly exposed to ephemeral apps
7249            if (!isEphemeralApp
7250                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7251                continue;
7252            }
7253            resolveInfos.remove(i);
7254        }
7255        return resolveInfos;
7256    }
7257
7258    /**
7259     * @param resolveInfos list of resolve infos in descending priority order
7260     * @return if the list contains a resolve info with non-negative priority
7261     */
7262    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7263        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7264    }
7265
7266    private static boolean hasWebURI(Intent intent) {
7267        if (intent.getData() == null) {
7268            return false;
7269        }
7270        final String scheme = intent.getScheme();
7271        if (TextUtils.isEmpty(scheme)) {
7272            return false;
7273        }
7274        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7275    }
7276
7277    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7278            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7279            int userId) {
7280        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7281
7282        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7283            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7284                    candidates.size());
7285        }
7286
7287        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7288        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7289        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7290        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7291        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7292        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7293
7294        synchronized (mPackages) {
7295            final int count = candidates.size();
7296            // First, try to use linked apps. Partition the candidates into four lists:
7297            // one for the final results, one for the "do not use ever", one for "undefined status"
7298            // and finally one for "browser app type".
7299            for (int n=0; n<count; n++) {
7300                ResolveInfo info = candidates.get(n);
7301                String packageName = info.activityInfo.packageName;
7302                PackageSetting ps = mSettings.mPackages.get(packageName);
7303                if (ps != null) {
7304                    // Add to the special match all list (Browser use case)
7305                    if (info.handleAllWebDataURI) {
7306                        matchAllList.add(info);
7307                        continue;
7308                    }
7309                    // Try to get the status from User settings first
7310                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7311                    int status = (int)(packedStatus >> 32);
7312                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7313                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7314                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7315                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7316                                    + " : linkgen=" + linkGeneration);
7317                        }
7318                        // Use link-enabled generation as preferredOrder, i.e.
7319                        // prefer newly-enabled over earlier-enabled.
7320                        info.preferredOrder = linkGeneration;
7321                        alwaysList.add(info);
7322                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7323                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7324                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7325                        }
7326                        neverList.add(info);
7327                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7328                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7329                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7330                        }
7331                        alwaysAskList.add(info);
7332                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7333                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7334                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7335                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7336                        }
7337                        undefinedList.add(info);
7338                    }
7339                }
7340            }
7341
7342            // We'll want to include browser possibilities in a few cases
7343            boolean includeBrowser = false;
7344
7345            // First try to add the "always" resolution(s) for the current user, if any
7346            if (alwaysList.size() > 0) {
7347                result.addAll(alwaysList);
7348            } else {
7349                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7350                result.addAll(undefinedList);
7351                // Maybe add one for the other profile.
7352                if (xpDomainInfo != null && (
7353                        xpDomainInfo.bestDomainVerificationStatus
7354                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7355                    result.add(xpDomainInfo.resolveInfo);
7356                }
7357                includeBrowser = true;
7358            }
7359
7360            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7361            // If there were 'always' entries their preferred order has been set, so we also
7362            // back that off to make the alternatives equivalent
7363            if (alwaysAskList.size() > 0) {
7364                for (ResolveInfo i : result) {
7365                    i.preferredOrder = 0;
7366                }
7367                result.addAll(alwaysAskList);
7368                includeBrowser = true;
7369            }
7370
7371            if (includeBrowser) {
7372                // Also add browsers (all of them or only the default one)
7373                if (DEBUG_DOMAIN_VERIFICATION) {
7374                    Slog.v(TAG, "   ...including browsers in candidate set");
7375                }
7376                if ((matchFlags & MATCH_ALL) != 0) {
7377                    result.addAll(matchAllList);
7378                } else {
7379                    // Browser/generic handling case.  If there's a default browser, go straight
7380                    // to that (but only if there is no other higher-priority match).
7381                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7382                    int maxMatchPrio = 0;
7383                    ResolveInfo defaultBrowserMatch = null;
7384                    final int numCandidates = matchAllList.size();
7385                    for (int n = 0; n < numCandidates; n++) {
7386                        ResolveInfo info = matchAllList.get(n);
7387                        // track the highest overall match priority...
7388                        if (info.priority > maxMatchPrio) {
7389                            maxMatchPrio = info.priority;
7390                        }
7391                        // ...and the highest-priority default browser match
7392                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7393                            if (defaultBrowserMatch == null
7394                                    || (defaultBrowserMatch.priority < info.priority)) {
7395                                if (debug) {
7396                                    Slog.v(TAG, "Considering default browser match " + info);
7397                                }
7398                                defaultBrowserMatch = info;
7399                            }
7400                        }
7401                    }
7402                    if (defaultBrowserMatch != null
7403                            && defaultBrowserMatch.priority >= maxMatchPrio
7404                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7405                    {
7406                        if (debug) {
7407                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7408                        }
7409                        result.add(defaultBrowserMatch);
7410                    } else {
7411                        result.addAll(matchAllList);
7412                    }
7413                }
7414
7415                // If there is nothing selected, add all candidates and remove the ones that the user
7416                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7417                if (result.size() == 0) {
7418                    result.addAll(candidates);
7419                    result.removeAll(neverList);
7420                }
7421            }
7422        }
7423        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7424            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7425                    result.size());
7426            for (ResolveInfo info : result) {
7427                Slog.v(TAG, "  + " + info.activityInfo);
7428            }
7429        }
7430        return result;
7431    }
7432
7433    // Returns a packed value as a long:
7434    //
7435    // high 'int'-sized word: link status: undefined/ask/never/always.
7436    // low 'int'-sized word: relative priority among 'always' results.
7437    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7438        long result = ps.getDomainVerificationStatusForUser(userId);
7439        // if none available, get the master status
7440        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7441            if (ps.getIntentFilterVerificationInfo() != null) {
7442                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7443            }
7444        }
7445        return result;
7446    }
7447
7448    private ResolveInfo querySkipCurrentProfileIntents(
7449            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7450            int flags, int sourceUserId) {
7451        if (matchingFilters != null) {
7452            int size = matchingFilters.size();
7453            for (int i = 0; i < size; i ++) {
7454                CrossProfileIntentFilter filter = matchingFilters.get(i);
7455                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7456                    // Checking if there are activities in the target user that can handle the
7457                    // intent.
7458                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7459                            resolvedType, flags, sourceUserId);
7460                    if (resolveInfo != null) {
7461                        return resolveInfo;
7462                    }
7463                }
7464            }
7465        }
7466        return null;
7467    }
7468
7469    // Return matching ResolveInfo in target user if any.
7470    private ResolveInfo queryCrossProfileIntents(
7471            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7472            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7473        if (matchingFilters != null) {
7474            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7475            // match the same intent. For performance reasons, it is better not to
7476            // run queryIntent twice for the same userId
7477            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7478            int size = matchingFilters.size();
7479            for (int i = 0; i < size; i++) {
7480                CrossProfileIntentFilter filter = matchingFilters.get(i);
7481                int targetUserId = filter.getTargetUserId();
7482                boolean skipCurrentProfile =
7483                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7484                boolean skipCurrentProfileIfNoMatchFound =
7485                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7486                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7487                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7488                    // Checking if there are activities in the target user that can handle the
7489                    // intent.
7490                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7491                            resolvedType, flags, sourceUserId);
7492                    if (resolveInfo != null) return resolveInfo;
7493                    alreadyTriedUserIds.put(targetUserId, true);
7494                }
7495            }
7496        }
7497        return null;
7498    }
7499
7500    /**
7501     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7502     * will forward the intent to the filter's target user.
7503     * Otherwise, returns null.
7504     */
7505    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7506            String resolvedType, int flags, int sourceUserId) {
7507        int targetUserId = filter.getTargetUserId();
7508        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7509                resolvedType, flags, targetUserId);
7510        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7511            // If all the matches in the target profile are suspended, return null.
7512            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7513                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7514                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7515                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7516                            targetUserId);
7517                }
7518            }
7519        }
7520        return null;
7521    }
7522
7523    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7524            int sourceUserId, int targetUserId) {
7525        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7526        long ident = Binder.clearCallingIdentity();
7527        boolean targetIsProfile;
7528        try {
7529            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7530        } finally {
7531            Binder.restoreCallingIdentity(ident);
7532        }
7533        String className;
7534        if (targetIsProfile) {
7535            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7536        } else {
7537            className = FORWARD_INTENT_TO_PARENT;
7538        }
7539        ComponentName forwardingActivityComponentName = new ComponentName(
7540                mAndroidApplication.packageName, className);
7541        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7542                sourceUserId);
7543        if (!targetIsProfile) {
7544            forwardingActivityInfo.showUserIcon = targetUserId;
7545            forwardingResolveInfo.noResourceId = true;
7546        }
7547        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7548        forwardingResolveInfo.priority = 0;
7549        forwardingResolveInfo.preferredOrder = 0;
7550        forwardingResolveInfo.match = 0;
7551        forwardingResolveInfo.isDefault = true;
7552        forwardingResolveInfo.filter = filter;
7553        forwardingResolveInfo.targetUserId = targetUserId;
7554        return forwardingResolveInfo;
7555    }
7556
7557    @Override
7558    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7559            Intent[] specifics, String[] specificTypes, Intent intent,
7560            String resolvedType, int flags, int userId) {
7561        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7562                specificTypes, intent, resolvedType, flags, userId));
7563    }
7564
7565    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7566            Intent[] specifics, String[] specificTypes, Intent intent,
7567            String resolvedType, int flags, int userId) {
7568        if (!sUserManager.exists(userId)) return Collections.emptyList();
7569        final int callingUid = Binder.getCallingUid();
7570        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7571                false /*includeInstantApps*/);
7572        enforceCrossUserPermission(callingUid, userId,
7573                false /*requireFullPermission*/, false /*checkShell*/,
7574                "query intent activity options");
7575        final String resultsAction = intent.getAction();
7576
7577        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7578                | PackageManager.GET_RESOLVED_FILTER, userId);
7579
7580        if (DEBUG_INTENT_MATCHING) {
7581            Log.v(TAG, "Query " + intent + ": " + results);
7582        }
7583
7584        int specificsPos = 0;
7585        int N;
7586
7587        // todo: note that the algorithm used here is O(N^2).  This
7588        // isn't a problem in our current environment, but if we start running
7589        // into situations where we have more than 5 or 10 matches then this
7590        // should probably be changed to something smarter...
7591
7592        // First we go through and resolve each of the specific items
7593        // that were supplied, taking care of removing any corresponding
7594        // duplicate items in the generic resolve list.
7595        if (specifics != null) {
7596            for (int i=0; i<specifics.length; i++) {
7597                final Intent sintent = specifics[i];
7598                if (sintent == null) {
7599                    continue;
7600                }
7601
7602                if (DEBUG_INTENT_MATCHING) {
7603                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7604                }
7605
7606                String action = sintent.getAction();
7607                if (resultsAction != null && resultsAction.equals(action)) {
7608                    // If this action was explicitly requested, then don't
7609                    // remove things that have it.
7610                    action = null;
7611                }
7612
7613                ResolveInfo ri = null;
7614                ActivityInfo ai = null;
7615
7616                ComponentName comp = sintent.getComponent();
7617                if (comp == null) {
7618                    ri = resolveIntent(
7619                        sintent,
7620                        specificTypes != null ? specificTypes[i] : null,
7621                            flags, userId);
7622                    if (ri == null) {
7623                        continue;
7624                    }
7625                    if (ri == mResolveInfo) {
7626                        // ACK!  Must do something better with this.
7627                    }
7628                    ai = ri.activityInfo;
7629                    comp = new ComponentName(ai.applicationInfo.packageName,
7630                            ai.name);
7631                } else {
7632                    ai = getActivityInfo(comp, flags, userId);
7633                    if (ai == null) {
7634                        continue;
7635                    }
7636                }
7637
7638                // Look for any generic query activities that are duplicates
7639                // of this specific one, and remove them from the results.
7640                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7641                N = results.size();
7642                int j;
7643                for (j=specificsPos; j<N; j++) {
7644                    ResolveInfo sri = results.get(j);
7645                    if ((sri.activityInfo.name.equals(comp.getClassName())
7646                            && sri.activityInfo.applicationInfo.packageName.equals(
7647                                    comp.getPackageName()))
7648                        || (action != null && sri.filter.matchAction(action))) {
7649                        results.remove(j);
7650                        if (DEBUG_INTENT_MATCHING) Log.v(
7651                            TAG, "Removing duplicate item from " + j
7652                            + " due to specific " + specificsPos);
7653                        if (ri == null) {
7654                            ri = sri;
7655                        }
7656                        j--;
7657                        N--;
7658                    }
7659                }
7660
7661                // Add this specific item to its proper place.
7662                if (ri == null) {
7663                    ri = new ResolveInfo();
7664                    ri.activityInfo = ai;
7665                }
7666                results.add(specificsPos, ri);
7667                ri.specificIndex = i;
7668                specificsPos++;
7669            }
7670        }
7671
7672        // Now we go through the remaining generic results and remove any
7673        // duplicate actions that are found here.
7674        N = results.size();
7675        for (int i=specificsPos; i<N-1; i++) {
7676            final ResolveInfo rii = results.get(i);
7677            if (rii.filter == null) {
7678                continue;
7679            }
7680
7681            // Iterate over all of the actions of this result's intent
7682            // filter...  typically this should be just one.
7683            final Iterator<String> it = rii.filter.actionsIterator();
7684            if (it == null) {
7685                continue;
7686            }
7687            while (it.hasNext()) {
7688                final String action = it.next();
7689                if (resultsAction != null && resultsAction.equals(action)) {
7690                    // If this action was explicitly requested, then don't
7691                    // remove things that have it.
7692                    continue;
7693                }
7694                for (int j=i+1; j<N; j++) {
7695                    final ResolveInfo rij = results.get(j);
7696                    if (rij.filter != null && rij.filter.hasAction(action)) {
7697                        results.remove(j);
7698                        if (DEBUG_INTENT_MATCHING) Log.v(
7699                            TAG, "Removing duplicate item from " + j
7700                            + " due to action " + action + " at " + i);
7701                        j--;
7702                        N--;
7703                    }
7704                }
7705            }
7706
7707            // If the caller didn't request filter information, drop it now
7708            // so we don't have to marshall/unmarshall it.
7709            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7710                rii.filter = null;
7711            }
7712        }
7713
7714        // Filter out the caller activity if so requested.
7715        if (caller != null) {
7716            N = results.size();
7717            for (int i=0; i<N; i++) {
7718                ActivityInfo ainfo = results.get(i).activityInfo;
7719                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7720                        && caller.getClassName().equals(ainfo.name)) {
7721                    results.remove(i);
7722                    break;
7723                }
7724            }
7725        }
7726
7727        // If the caller didn't request filter information,
7728        // drop them now so we don't have to
7729        // marshall/unmarshall it.
7730        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7731            N = results.size();
7732            for (int i=0; i<N; i++) {
7733                results.get(i).filter = null;
7734            }
7735        }
7736
7737        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7738        return results;
7739    }
7740
7741    @Override
7742    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7743            String resolvedType, int flags, int userId) {
7744        return new ParceledListSlice<>(
7745                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7746    }
7747
7748    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7749            String resolvedType, int flags, int userId) {
7750        if (!sUserManager.exists(userId)) return Collections.emptyList();
7751        final int callingUid = Binder.getCallingUid();
7752        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7753        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7754                false /*includeInstantApps*/);
7755        ComponentName comp = intent.getComponent();
7756        if (comp == null) {
7757            if (intent.getSelector() != null) {
7758                intent = intent.getSelector();
7759                comp = intent.getComponent();
7760            }
7761        }
7762        if (comp != null) {
7763            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7764            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7765            if (ai != null) {
7766                // When specifying an explicit component, we prevent the activity from being
7767                // used when either 1) the calling package is normal and the activity is within
7768                // an instant application or 2) the calling package is ephemeral and the
7769                // activity is not visible to instant applications.
7770                final boolean matchInstantApp =
7771                        (flags & PackageManager.MATCH_INSTANT) != 0;
7772                final boolean matchVisibleToInstantAppOnly =
7773                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7774                final boolean matchExplicitlyVisibleOnly =
7775                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7776                final boolean isCallerInstantApp =
7777                        instantAppPkgName != null;
7778                final boolean isTargetSameInstantApp =
7779                        comp.getPackageName().equals(instantAppPkgName);
7780                final boolean isTargetInstantApp =
7781                        (ai.applicationInfo.privateFlags
7782                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7783                final boolean isTargetVisibleToInstantApp =
7784                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7785                final boolean isTargetExplicitlyVisibleToInstantApp =
7786                        isTargetVisibleToInstantApp
7787                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7788                final boolean isTargetHiddenFromInstantApp =
7789                        !isTargetVisibleToInstantApp
7790                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7791                final boolean blockResolution =
7792                        !isTargetSameInstantApp
7793                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7794                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7795                                        && isTargetHiddenFromInstantApp));
7796                if (!blockResolution) {
7797                    ResolveInfo ri = new ResolveInfo();
7798                    ri.activityInfo = ai;
7799                    list.add(ri);
7800                }
7801            }
7802            return applyPostResolutionFilter(list, instantAppPkgName);
7803        }
7804
7805        // reader
7806        synchronized (mPackages) {
7807            String pkgName = intent.getPackage();
7808            if (pkgName == null) {
7809                final List<ResolveInfo> result =
7810                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7811                return applyPostResolutionFilter(result, instantAppPkgName);
7812            }
7813            final PackageParser.Package pkg = mPackages.get(pkgName);
7814            if (pkg != null) {
7815                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7816                        intent, resolvedType, flags, pkg.receivers, userId);
7817                return applyPostResolutionFilter(result, instantAppPkgName);
7818            }
7819            return Collections.emptyList();
7820        }
7821    }
7822
7823    @Override
7824    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7825        final int callingUid = Binder.getCallingUid();
7826        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7827    }
7828
7829    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7830            int userId, int callingUid) {
7831        if (!sUserManager.exists(userId)) return null;
7832        flags = updateFlagsForResolve(
7833                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7834        List<ResolveInfo> query = queryIntentServicesInternal(
7835                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7836        if (query != null) {
7837            if (query.size() >= 1) {
7838                // If there is more than one service with the same priority,
7839                // just arbitrarily pick the first one.
7840                return query.get(0);
7841            }
7842        }
7843        return null;
7844    }
7845
7846    @Override
7847    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7848            String resolvedType, int flags, int userId) {
7849        final int callingUid = Binder.getCallingUid();
7850        return new ParceledListSlice<>(queryIntentServicesInternal(
7851                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7852    }
7853
7854    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7855            String resolvedType, int flags, int userId, int callingUid,
7856            boolean includeInstantApps) {
7857        if (!sUserManager.exists(userId)) return Collections.emptyList();
7858        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7859        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7860        ComponentName comp = intent.getComponent();
7861        if (comp == null) {
7862            if (intent.getSelector() != null) {
7863                intent = intent.getSelector();
7864                comp = intent.getComponent();
7865            }
7866        }
7867        if (comp != null) {
7868            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7869            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7870            if (si != null) {
7871                // When specifying an explicit component, we prevent the service from being
7872                // used when either 1) the service is in an instant application and the
7873                // caller is not the same instant application or 2) the calling package is
7874                // ephemeral and the activity is not visible to ephemeral applications.
7875                final boolean matchInstantApp =
7876                        (flags & PackageManager.MATCH_INSTANT) != 0;
7877                final boolean matchVisibleToInstantAppOnly =
7878                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7879                final boolean isCallerInstantApp =
7880                        instantAppPkgName != null;
7881                final boolean isTargetSameInstantApp =
7882                        comp.getPackageName().equals(instantAppPkgName);
7883                final boolean isTargetInstantApp =
7884                        (si.applicationInfo.privateFlags
7885                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7886                final boolean isTargetHiddenFromInstantApp =
7887                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7888                final boolean blockResolution =
7889                        !isTargetSameInstantApp
7890                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7891                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7892                                        && isTargetHiddenFromInstantApp));
7893                if (!blockResolution) {
7894                    final ResolveInfo ri = new ResolveInfo();
7895                    ri.serviceInfo = si;
7896                    list.add(ri);
7897                }
7898            }
7899            return list;
7900        }
7901
7902        // reader
7903        synchronized (mPackages) {
7904            String pkgName = intent.getPackage();
7905            if (pkgName == null) {
7906                return applyPostServiceResolutionFilter(
7907                        mServices.queryIntent(intent, resolvedType, flags, userId),
7908                        instantAppPkgName);
7909            }
7910            final PackageParser.Package pkg = mPackages.get(pkgName);
7911            if (pkg != null) {
7912                return applyPostServiceResolutionFilter(
7913                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7914                                userId),
7915                        instantAppPkgName);
7916            }
7917            return Collections.emptyList();
7918        }
7919    }
7920
7921    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7922            String instantAppPkgName) {
7923        // TODO: When adding on-demand split support for non-instant apps, remove this check
7924        // and always apply post filtering
7925        if (instantAppPkgName == null) {
7926            return resolveInfos;
7927        }
7928        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7929            final ResolveInfo info = resolveInfos.get(i);
7930            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7931            // allow services that are defined in the provided package
7932            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7933                if (info.serviceInfo.splitName != null
7934                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7935                                info.serviceInfo.splitName)) {
7936                    // requested service is defined in a split that hasn't been installed yet.
7937                    // add the installer to the resolve list
7938                    if (DEBUG_EPHEMERAL) {
7939                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7940                    }
7941                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7942                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7943                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7944                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7945                    // make sure this resolver is the default
7946                    installerInfo.isDefault = true;
7947                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7948                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7949                    // add a non-generic filter
7950                    installerInfo.filter = new IntentFilter();
7951                    // load resources from the correct package
7952                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7953                    resolveInfos.set(i, installerInfo);
7954                }
7955                continue;
7956            }
7957            // allow services that have been explicitly exposed to ephemeral apps
7958            if (!isEphemeralApp
7959                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7960                continue;
7961            }
7962            resolveInfos.remove(i);
7963        }
7964        return resolveInfos;
7965    }
7966
7967    @Override
7968    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7969            String resolvedType, int flags, int userId) {
7970        return new ParceledListSlice<>(
7971                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7972    }
7973
7974    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7975            Intent intent, String resolvedType, int flags, int userId) {
7976        if (!sUserManager.exists(userId)) return Collections.emptyList();
7977        final int callingUid = Binder.getCallingUid();
7978        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7979        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7980                false /*includeInstantApps*/);
7981        ComponentName comp = intent.getComponent();
7982        if (comp == null) {
7983            if (intent.getSelector() != null) {
7984                intent = intent.getSelector();
7985                comp = intent.getComponent();
7986            }
7987        }
7988        if (comp != null) {
7989            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7990            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7991            if (pi != null) {
7992                // When specifying an explicit component, we prevent the provider from being
7993                // used when either 1) the provider is in an instant application and the
7994                // caller is not the same instant application or 2) the calling package is an
7995                // instant application and the provider is not visible to instant applications.
7996                final boolean matchInstantApp =
7997                        (flags & PackageManager.MATCH_INSTANT) != 0;
7998                final boolean matchVisibleToInstantAppOnly =
7999                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8000                final boolean isCallerInstantApp =
8001                        instantAppPkgName != null;
8002                final boolean isTargetSameInstantApp =
8003                        comp.getPackageName().equals(instantAppPkgName);
8004                final boolean isTargetInstantApp =
8005                        (pi.applicationInfo.privateFlags
8006                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8007                final boolean isTargetHiddenFromInstantApp =
8008                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8009                final boolean blockResolution =
8010                        !isTargetSameInstantApp
8011                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8012                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8013                                        && isTargetHiddenFromInstantApp));
8014                if (!blockResolution) {
8015                    final ResolveInfo ri = new ResolveInfo();
8016                    ri.providerInfo = pi;
8017                    list.add(ri);
8018                }
8019            }
8020            return list;
8021        }
8022
8023        // reader
8024        synchronized (mPackages) {
8025            String pkgName = intent.getPackage();
8026            if (pkgName == null) {
8027                return applyPostContentProviderResolutionFilter(
8028                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8029                        instantAppPkgName);
8030            }
8031            final PackageParser.Package pkg = mPackages.get(pkgName);
8032            if (pkg != null) {
8033                return applyPostContentProviderResolutionFilter(
8034                        mProviders.queryIntentForPackage(
8035                        intent, resolvedType, flags, pkg.providers, userId),
8036                        instantAppPkgName);
8037            }
8038            return Collections.emptyList();
8039        }
8040    }
8041
8042    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8043            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8044        // TODO: When adding on-demand split support for non-instant applications, remove
8045        // this check and always apply post filtering
8046        if (instantAppPkgName == null) {
8047            return resolveInfos;
8048        }
8049        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8050            final ResolveInfo info = resolveInfos.get(i);
8051            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8052            // allow providers that are defined in the provided package
8053            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8054                if (info.providerInfo.splitName != null
8055                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8056                                info.providerInfo.splitName)) {
8057                    // requested provider is defined in a split that hasn't been installed yet.
8058                    // add the installer to the resolve list
8059                    if (DEBUG_EPHEMERAL) {
8060                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8061                    }
8062                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8063                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8064                            info.providerInfo.packageName, info.providerInfo.splitName,
8065                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8066                    // make sure this resolver is the default
8067                    installerInfo.isDefault = true;
8068                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8069                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8070                    // add a non-generic filter
8071                    installerInfo.filter = new IntentFilter();
8072                    // load resources from the correct package
8073                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8074                    resolveInfos.set(i, installerInfo);
8075                }
8076                continue;
8077            }
8078            // allow providers that have been explicitly exposed to instant applications
8079            if (!isEphemeralApp
8080                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8081                continue;
8082            }
8083            resolveInfos.remove(i);
8084        }
8085        return resolveInfos;
8086    }
8087
8088    @Override
8089    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8090        final int callingUid = Binder.getCallingUid();
8091        if (getInstantAppPackageName(callingUid) != null) {
8092            return ParceledListSlice.emptyList();
8093        }
8094        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8095        flags = updateFlagsForPackage(flags, userId, null);
8096        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8097        enforceCrossUserPermission(callingUid, userId,
8098                true /* requireFullPermission */, false /* checkShell */,
8099                "get installed packages");
8100
8101        // writer
8102        synchronized (mPackages) {
8103            ArrayList<PackageInfo> list;
8104            if (listUninstalled) {
8105                list = new ArrayList<>(mSettings.mPackages.size());
8106                for (PackageSetting ps : mSettings.mPackages.values()) {
8107                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8108                        continue;
8109                    }
8110                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8111                        return null;
8112                    }
8113                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8114                    if (pi != null) {
8115                        list.add(pi);
8116                    }
8117                }
8118            } else {
8119                list = new ArrayList<>(mPackages.size());
8120                for (PackageParser.Package p : mPackages.values()) {
8121                    final PackageSetting ps = (PackageSetting) p.mExtras;
8122                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8123                        continue;
8124                    }
8125                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8126                        return null;
8127                    }
8128                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8129                            p.mExtras, flags, userId);
8130                    if (pi != null) {
8131                        list.add(pi);
8132                    }
8133                }
8134            }
8135
8136            return new ParceledListSlice<>(list);
8137        }
8138    }
8139
8140    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8141            String[] permissions, boolean[] tmp, int flags, int userId) {
8142        int numMatch = 0;
8143        final PermissionsState permissionsState = ps.getPermissionsState();
8144        for (int i=0; i<permissions.length; i++) {
8145            final String permission = permissions[i];
8146            if (permissionsState.hasPermission(permission, userId)) {
8147                tmp[i] = true;
8148                numMatch++;
8149            } else {
8150                tmp[i] = false;
8151            }
8152        }
8153        if (numMatch == 0) {
8154            return;
8155        }
8156        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8157
8158        // The above might return null in cases of uninstalled apps or install-state
8159        // skew across users/profiles.
8160        if (pi != null) {
8161            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8162                if (numMatch == permissions.length) {
8163                    pi.requestedPermissions = permissions;
8164                } else {
8165                    pi.requestedPermissions = new String[numMatch];
8166                    numMatch = 0;
8167                    for (int i=0; i<permissions.length; i++) {
8168                        if (tmp[i]) {
8169                            pi.requestedPermissions[numMatch] = permissions[i];
8170                            numMatch++;
8171                        }
8172                    }
8173                }
8174            }
8175            list.add(pi);
8176        }
8177    }
8178
8179    @Override
8180    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8181            String[] permissions, int flags, int userId) {
8182        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8183        flags = updateFlagsForPackage(flags, userId, permissions);
8184        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8185                true /* requireFullPermission */, false /* checkShell */,
8186                "get packages holding permissions");
8187        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8188
8189        // writer
8190        synchronized (mPackages) {
8191            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8192            boolean[] tmpBools = new boolean[permissions.length];
8193            if (listUninstalled) {
8194                for (PackageSetting ps : mSettings.mPackages.values()) {
8195                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8196                            userId);
8197                }
8198            } else {
8199                for (PackageParser.Package pkg : mPackages.values()) {
8200                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8201                    if (ps != null) {
8202                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8203                                userId);
8204                    }
8205                }
8206            }
8207
8208            return new ParceledListSlice<PackageInfo>(list);
8209        }
8210    }
8211
8212    @Override
8213    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8214        final int callingUid = Binder.getCallingUid();
8215        if (getInstantAppPackageName(callingUid) != null) {
8216            return ParceledListSlice.emptyList();
8217        }
8218        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8219        flags = updateFlagsForApplication(flags, userId, null);
8220        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8221
8222        // writer
8223        synchronized (mPackages) {
8224            ArrayList<ApplicationInfo> list;
8225            if (listUninstalled) {
8226                list = new ArrayList<>(mSettings.mPackages.size());
8227                for (PackageSetting ps : mSettings.mPackages.values()) {
8228                    ApplicationInfo ai;
8229                    int effectiveFlags = flags;
8230                    if (ps.isSystem()) {
8231                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8232                    }
8233                    if (ps.pkg != null) {
8234                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8235                            continue;
8236                        }
8237                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8238                            return null;
8239                        }
8240                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8241                                ps.readUserState(userId), userId);
8242                        if (ai != null) {
8243                            rebaseEnabledOverlays(ai, userId);
8244                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8245                        }
8246                    } else {
8247                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8248                        // and already converts to externally visible package name
8249                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8250                                callingUid, effectiveFlags, userId);
8251                    }
8252                    if (ai != null) {
8253                        list.add(ai);
8254                    }
8255                }
8256            } else {
8257                list = new ArrayList<>(mPackages.size());
8258                for (PackageParser.Package p : mPackages.values()) {
8259                    if (p.mExtras != null) {
8260                        PackageSetting ps = (PackageSetting) p.mExtras;
8261                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8262                            continue;
8263                        }
8264                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8265                            return null;
8266                        }
8267                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8268                                ps.readUserState(userId), userId);
8269                        if (ai != null) {
8270                            rebaseEnabledOverlays(ai, userId);
8271                            ai.packageName = resolveExternalPackageNameLPr(p);
8272                            list.add(ai);
8273                        }
8274                    }
8275                }
8276            }
8277
8278            return new ParceledListSlice<>(list);
8279        }
8280    }
8281
8282    @Override
8283    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8284        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8285            return null;
8286        }
8287        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8288                "getEphemeralApplications");
8289        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8290                true /* requireFullPermission */, false /* checkShell */,
8291                "getEphemeralApplications");
8292        synchronized (mPackages) {
8293            List<InstantAppInfo> instantApps = mInstantAppRegistry
8294                    .getInstantAppsLPr(userId);
8295            if (instantApps != null) {
8296                return new ParceledListSlice<>(instantApps);
8297            }
8298        }
8299        return null;
8300    }
8301
8302    @Override
8303    public boolean isInstantApp(String packageName, int userId) {
8304        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8305                true /* requireFullPermission */, false /* checkShell */,
8306                "isInstantApp");
8307        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8308            return false;
8309        }
8310        int callingUid = Binder.getCallingUid();
8311        if (Process.isIsolated(callingUid)) {
8312            callingUid = mIsolatedOwners.get(callingUid);
8313        }
8314
8315        synchronized (mPackages) {
8316            final PackageSetting ps = mSettings.mPackages.get(packageName);
8317            PackageParser.Package pkg = mPackages.get(packageName);
8318            final boolean returnAllowed =
8319                    ps != null
8320                    && (isCallerSameApp(packageName, callingUid)
8321                            || canViewInstantApps(callingUid, userId)
8322                            || mInstantAppRegistry.isInstantAccessGranted(
8323                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8324            if (returnAllowed) {
8325                return ps.getInstantApp(userId);
8326            }
8327        }
8328        return false;
8329    }
8330
8331    @Override
8332    public byte[] getInstantAppCookie(String packageName, int userId) {
8333        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8334            return null;
8335        }
8336
8337        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8338                true /* requireFullPermission */, false /* checkShell */,
8339                "getInstantAppCookie");
8340        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8341            return null;
8342        }
8343        synchronized (mPackages) {
8344            return mInstantAppRegistry.getInstantAppCookieLPw(
8345                    packageName, userId);
8346        }
8347    }
8348
8349    @Override
8350    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8351        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8352            return true;
8353        }
8354
8355        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8356                true /* requireFullPermission */, true /* checkShell */,
8357                "setInstantAppCookie");
8358        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8359            return false;
8360        }
8361        synchronized (mPackages) {
8362            return mInstantAppRegistry.setInstantAppCookieLPw(
8363                    packageName, cookie, userId);
8364        }
8365    }
8366
8367    @Override
8368    public Bitmap getInstantAppIcon(String packageName, int userId) {
8369        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8370            return null;
8371        }
8372
8373        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8374                "getInstantAppIcon");
8375
8376        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8377                true /* requireFullPermission */, false /* checkShell */,
8378                "getInstantAppIcon");
8379
8380        synchronized (mPackages) {
8381            return mInstantAppRegistry.getInstantAppIconLPw(
8382                    packageName, userId);
8383        }
8384    }
8385
8386    private boolean isCallerSameApp(String packageName, int uid) {
8387        PackageParser.Package pkg = mPackages.get(packageName);
8388        return pkg != null
8389                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8390    }
8391
8392    @Override
8393    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8394        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8395            return ParceledListSlice.emptyList();
8396        }
8397        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8398    }
8399
8400    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8401        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8402
8403        // reader
8404        synchronized (mPackages) {
8405            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8406            final int userId = UserHandle.getCallingUserId();
8407            while (i.hasNext()) {
8408                final PackageParser.Package p = i.next();
8409                if (p.applicationInfo == null) continue;
8410
8411                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8412                        && !p.applicationInfo.isDirectBootAware();
8413                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8414                        && p.applicationInfo.isDirectBootAware();
8415
8416                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8417                        && (!mSafeMode || isSystemApp(p))
8418                        && (matchesUnaware || matchesAware)) {
8419                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8420                    if (ps != null) {
8421                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8422                                ps.readUserState(userId), userId);
8423                        if (ai != null) {
8424                            rebaseEnabledOverlays(ai, userId);
8425                            finalList.add(ai);
8426                        }
8427                    }
8428                }
8429            }
8430        }
8431
8432        return finalList;
8433    }
8434
8435    @Override
8436    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8437        if (!sUserManager.exists(userId)) return null;
8438        flags = updateFlagsForComponent(flags, userId, name);
8439        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8440        // reader
8441        synchronized (mPackages) {
8442            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8443            PackageSetting ps = provider != null
8444                    ? mSettings.mPackages.get(provider.owner.packageName)
8445                    : null;
8446            if (ps != null) {
8447                final boolean isInstantApp = ps.getInstantApp(userId);
8448                // normal application; filter out instant application provider
8449                if (instantAppPkgName == null && isInstantApp) {
8450                    return null;
8451                }
8452                // instant application; filter out other instant applications
8453                if (instantAppPkgName != null
8454                        && isInstantApp
8455                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8456                    return null;
8457                }
8458                // instant application; filter out non-exposed provider
8459                if (instantAppPkgName != null
8460                        && !isInstantApp
8461                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8462                    return null;
8463                }
8464                // provider not enabled
8465                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8466                    return null;
8467                }
8468                return PackageParser.generateProviderInfo(
8469                        provider, flags, ps.readUserState(userId), userId);
8470            }
8471            return null;
8472        }
8473    }
8474
8475    /**
8476     * @deprecated
8477     */
8478    @Deprecated
8479    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8480        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8481            return;
8482        }
8483        // reader
8484        synchronized (mPackages) {
8485            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8486                    .entrySet().iterator();
8487            final int userId = UserHandle.getCallingUserId();
8488            while (i.hasNext()) {
8489                Map.Entry<String, PackageParser.Provider> entry = i.next();
8490                PackageParser.Provider p = entry.getValue();
8491                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8492
8493                if (ps != null && p.syncable
8494                        && (!mSafeMode || (p.info.applicationInfo.flags
8495                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8496                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8497                            ps.readUserState(userId), userId);
8498                    if (info != null) {
8499                        outNames.add(entry.getKey());
8500                        outInfo.add(info);
8501                    }
8502                }
8503            }
8504        }
8505    }
8506
8507    @Override
8508    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8509            int uid, int flags, String metaDataKey) {
8510        final int callingUid = Binder.getCallingUid();
8511        final int userId = processName != null ? UserHandle.getUserId(uid)
8512                : UserHandle.getCallingUserId();
8513        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8514        flags = updateFlagsForComponent(flags, userId, processName);
8515        ArrayList<ProviderInfo> finalList = null;
8516        // reader
8517        synchronized (mPackages) {
8518            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8519            while (i.hasNext()) {
8520                final PackageParser.Provider p = i.next();
8521                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8522                if (ps != null && p.info.authority != null
8523                        && (processName == null
8524                                || (p.info.processName.equals(processName)
8525                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8526                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8527
8528                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8529                    // parameter.
8530                    if (metaDataKey != null
8531                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8532                        continue;
8533                    }
8534                    final ComponentName component =
8535                            new ComponentName(p.info.packageName, p.info.name);
8536                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8537                        continue;
8538                    }
8539                    if (finalList == null) {
8540                        finalList = new ArrayList<ProviderInfo>(3);
8541                    }
8542                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8543                            ps.readUserState(userId), userId);
8544                    if (info != null) {
8545                        finalList.add(info);
8546                    }
8547                }
8548            }
8549        }
8550
8551        if (finalList != null) {
8552            Collections.sort(finalList, mProviderInitOrderSorter);
8553            return new ParceledListSlice<ProviderInfo>(finalList);
8554        }
8555
8556        return ParceledListSlice.emptyList();
8557    }
8558
8559    @Override
8560    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8561        // reader
8562        synchronized (mPackages) {
8563            final int callingUid = Binder.getCallingUid();
8564            final int callingUserId = UserHandle.getUserId(callingUid);
8565            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8566            if (ps == null) return null;
8567            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8568                return null;
8569            }
8570            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8571            return PackageParser.generateInstrumentationInfo(i, flags);
8572        }
8573    }
8574
8575    @Override
8576    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8577            String targetPackage, int flags) {
8578        final int callingUid = Binder.getCallingUid();
8579        final int callingUserId = UserHandle.getUserId(callingUid);
8580        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8581        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8582            return ParceledListSlice.emptyList();
8583        }
8584        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8585    }
8586
8587    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8588            int flags) {
8589        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8590
8591        // reader
8592        synchronized (mPackages) {
8593            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8594            while (i.hasNext()) {
8595                final PackageParser.Instrumentation p = i.next();
8596                if (targetPackage == null
8597                        || targetPackage.equals(p.info.targetPackage)) {
8598                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8599                            flags);
8600                    if (ii != null) {
8601                        finalList.add(ii);
8602                    }
8603                }
8604            }
8605        }
8606
8607        return finalList;
8608    }
8609
8610    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8611        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8612        try {
8613            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8614        } finally {
8615            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8616        }
8617    }
8618
8619    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8620        final File[] files = dir.listFiles();
8621        if (ArrayUtils.isEmpty(files)) {
8622            Log.d(TAG, "No files in app dir " + dir);
8623            return;
8624        }
8625
8626        if (DEBUG_PACKAGE_SCANNING) {
8627            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8628                    + " flags=0x" + Integer.toHexString(parseFlags));
8629        }
8630        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8631                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8632                mParallelPackageParserCallback);
8633
8634        // Submit files for parsing in parallel
8635        int fileCount = 0;
8636        for (File file : files) {
8637            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8638                    && !PackageInstallerService.isStageName(file.getName());
8639            if (!isPackage) {
8640                // Ignore entries which are not packages
8641                continue;
8642            }
8643            parallelPackageParser.submit(file, parseFlags);
8644            fileCount++;
8645        }
8646
8647        // Process results one by one
8648        for (; fileCount > 0; fileCount--) {
8649            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8650            Throwable throwable = parseResult.throwable;
8651            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8652
8653            if (throwable == null) {
8654                // Static shared libraries have synthetic package names
8655                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8656                    renameStaticSharedLibraryPackage(parseResult.pkg);
8657                }
8658                try {
8659                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8660                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8661                                currentTime, null);
8662                    }
8663                } catch (PackageManagerException e) {
8664                    errorCode = e.error;
8665                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8666                }
8667            } else if (throwable instanceof PackageParser.PackageParserException) {
8668                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8669                        throwable;
8670                errorCode = e.error;
8671                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8672            } else {
8673                throw new IllegalStateException("Unexpected exception occurred while parsing "
8674                        + parseResult.scanFile, throwable);
8675            }
8676
8677            // Delete invalid userdata apps
8678            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8679                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8680                logCriticalInfo(Log.WARN,
8681                        "Deleting invalid package at " + parseResult.scanFile);
8682                removeCodePathLI(parseResult.scanFile);
8683            }
8684        }
8685        parallelPackageParser.close();
8686    }
8687
8688    private static File getSettingsProblemFile() {
8689        File dataDir = Environment.getDataDirectory();
8690        File systemDir = new File(dataDir, "system");
8691        File fname = new File(systemDir, "uiderrors.txt");
8692        return fname;
8693    }
8694
8695    static void reportSettingsProblem(int priority, String msg) {
8696        logCriticalInfo(priority, msg);
8697    }
8698
8699    public static void logCriticalInfo(int priority, String msg) {
8700        Slog.println(priority, TAG, msg);
8701        EventLogTags.writePmCriticalInfo(msg);
8702        try {
8703            File fname = getSettingsProblemFile();
8704            FileOutputStream out = new FileOutputStream(fname, true);
8705            PrintWriter pw = new FastPrintWriter(out);
8706            SimpleDateFormat formatter = new SimpleDateFormat();
8707            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8708            pw.println(dateString + ": " + msg);
8709            pw.close();
8710            FileUtils.setPermissions(
8711                    fname.toString(),
8712                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8713                    -1, -1);
8714        } catch (java.io.IOException e) {
8715        }
8716    }
8717
8718    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8719        if (srcFile.isDirectory()) {
8720            final File baseFile = new File(pkg.baseCodePath);
8721            long maxModifiedTime = baseFile.lastModified();
8722            if (pkg.splitCodePaths != null) {
8723                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8724                    final File splitFile = new File(pkg.splitCodePaths[i]);
8725                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8726                }
8727            }
8728            return maxModifiedTime;
8729        }
8730        return srcFile.lastModified();
8731    }
8732
8733    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8734            final int policyFlags) throws PackageManagerException {
8735        // When upgrading from pre-N MR1, verify the package time stamp using the package
8736        // directory and not the APK file.
8737        final long lastModifiedTime = mIsPreNMR1Upgrade
8738                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8739        if (ps != null
8740                && ps.codePath.equals(srcFile)
8741                && ps.timeStamp == lastModifiedTime
8742                && !isCompatSignatureUpdateNeeded(pkg)
8743                && !isRecoverSignatureUpdateNeeded(pkg)) {
8744            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8745            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8746            ArraySet<PublicKey> signingKs;
8747            synchronized (mPackages) {
8748                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8749            }
8750            if (ps.signatures.mSignatures != null
8751                    && ps.signatures.mSignatures.length != 0
8752                    && signingKs != null) {
8753                // Optimization: reuse the existing cached certificates
8754                // if the package appears to be unchanged.
8755                pkg.mSignatures = ps.signatures.mSignatures;
8756                pkg.mSigningKeys = signingKs;
8757                return;
8758            }
8759
8760            Slog.w(TAG, "PackageSetting for " + ps.name
8761                    + " is missing signatures.  Collecting certs again to recover them.");
8762        } else {
8763            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8764        }
8765
8766        try {
8767            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8768            PackageParser.collectCertificates(pkg, policyFlags);
8769        } catch (PackageParserException e) {
8770            throw PackageManagerException.from(e);
8771        } finally {
8772            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8773        }
8774    }
8775
8776    /**
8777     *  Traces a package scan.
8778     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8779     */
8780    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8781            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8782        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8783        try {
8784            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8785        } finally {
8786            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8787        }
8788    }
8789
8790    /**
8791     *  Scans a package and returns the newly parsed package.
8792     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8793     */
8794    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8795            long currentTime, UserHandle user) throws PackageManagerException {
8796        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8797        PackageParser pp = new PackageParser();
8798        pp.setSeparateProcesses(mSeparateProcesses);
8799        pp.setOnlyCoreApps(mOnlyCore);
8800        pp.setDisplayMetrics(mMetrics);
8801        pp.setCallback(mPackageParserCallback);
8802
8803        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8804            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8805        }
8806
8807        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8808        final PackageParser.Package pkg;
8809        try {
8810            pkg = pp.parsePackage(scanFile, parseFlags);
8811        } catch (PackageParserException e) {
8812            throw PackageManagerException.from(e);
8813        } finally {
8814            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8815        }
8816
8817        // Static shared libraries have synthetic package names
8818        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8819            renameStaticSharedLibraryPackage(pkg);
8820        }
8821
8822        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8823    }
8824
8825    /**
8826     *  Scans a package and returns the newly parsed package.
8827     *  @throws PackageManagerException on a parse error.
8828     */
8829    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8830            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8831            throws PackageManagerException {
8832        // If the package has children and this is the first dive in the function
8833        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8834        // packages (parent and children) would be successfully scanned before the
8835        // actual scan since scanning mutates internal state and we want to atomically
8836        // install the package and its children.
8837        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8838            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8839                scanFlags |= SCAN_CHECK_ONLY;
8840            }
8841        } else {
8842            scanFlags &= ~SCAN_CHECK_ONLY;
8843        }
8844
8845        // Scan the parent
8846        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8847                scanFlags, currentTime, user);
8848
8849        // Scan the children
8850        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8851        for (int i = 0; i < childCount; i++) {
8852            PackageParser.Package childPackage = pkg.childPackages.get(i);
8853            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8854                    currentTime, user);
8855        }
8856
8857
8858        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8859            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8860        }
8861
8862        return scannedPkg;
8863    }
8864
8865    /**
8866     *  Scans a package and returns the newly parsed package.
8867     *  @throws PackageManagerException on a parse error.
8868     */
8869    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8870            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8871            throws PackageManagerException {
8872        PackageSetting ps = null;
8873        PackageSetting updatedPkg;
8874        // reader
8875        synchronized (mPackages) {
8876            // Look to see if we already know about this package.
8877            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8878            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8879                // This package has been renamed to its original name.  Let's
8880                // use that.
8881                ps = mSettings.getPackageLPr(oldName);
8882            }
8883            // If there was no original package, see one for the real package name.
8884            if (ps == null) {
8885                ps = mSettings.getPackageLPr(pkg.packageName);
8886            }
8887            // Check to see if this package could be hiding/updating a system
8888            // package.  Must look for it either under the original or real
8889            // package name depending on our state.
8890            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8891            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8892
8893            // If this is a package we don't know about on the system partition, we
8894            // may need to remove disabled child packages on the system partition
8895            // or may need to not add child packages if the parent apk is updated
8896            // on the data partition and no longer defines this child package.
8897            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8898                // If this is a parent package for an updated system app and this system
8899                // app got an OTA update which no longer defines some of the child packages
8900                // we have to prune them from the disabled system packages.
8901                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8902                if (disabledPs != null) {
8903                    final int scannedChildCount = (pkg.childPackages != null)
8904                            ? pkg.childPackages.size() : 0;
8905                    final int disabledChildCount = disabledPs.childPackageNames != null
8906                            ? disabledPs.childPackageNames.size() : 0;
8907                    for (int i = 0; i < disabledChildCount; i++) {
8908                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8909                        boolean disabledPackageAvailable = false;
8910                        for (int j = 0; j < scannedChildCount; j++) {
8911                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8912                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8913                                disabledPackageAvailable = true;
8914                                break;
8915                            }
8916                         }
8917                         if (!disabledPackageAvailable) {
8918                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8919                         }
8920                    }
8921                }
8922            }
8923        }
8924
8925        boolean updatedPkgBetter = false;
8926        // First check if this is a system package that may involve an update
8927        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8928            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8929            // it needs to drop FLAG_PRIVILEGED.
8930            if (locationIsPrivileged(scanFile)) {
8931                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8932            } else {
8933                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8934            }
8935
8936            if (ps != null && !ps.codePath.equals(scanFile)) {
8937                // The path has changed from what was last scanned...  check the
8938                // version of the new path against what we have stored to determine
8939                // what to do.
8940                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8941                if (pkg.mVersionCode <= ps.versionCode) {
8942                    // The system package has been updated and the code path does not match
8943                    // Ignore entry. Skip it.
8944                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8945                            + " ignored: updated version " + ps.versionCode
8946                            + " better than this " + pkg.mVersionCode);
8947                    if (!updatedPkg.codePath.equals(scanFile)) {
8948                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8949                                + ps.name + " changing from " + updatedPkg.codePathString
8950                                + " to " + scanFile);
8951                        updatedPkg.codePath = scanFile;
8952                        updatedPkg.codePathString = scanFile.toString();
8953                        updatedPkg.resourcePath = scanFile;
8954                        updatedPkg.resourcePathString = scanFile.toString();
8955                    }
8956                    updatedPkg.pkg = pkg;
8957                    updatedPkg.versionCode = pkg.mVersionCode;
8958
8959                    // Update the disabled system child packages to point to the package too.
8960                    final int childCount = updatedPkg.childPackageNames != null
8961                            ? updatedPkg.childPackageNames.size() : 0;
8962                    for (int i = 0; i < childCount; i++) {
8963                        String childPackageName = updatedPkg.childPackageNames.get(i);
8964                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8965                                childPackageName);
8966                        if (updatedChildPkg != null) {
8967                            updatedChildPkg.pkg = pkg;
8968                            updatedChildPkg.versionCode = pkg.mVersionCode;
8969                        }
8970                    }
8971
8972                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8973                            + scanFile + " ignored: updated version " + ps.versionCode
8974                            + " better than this " + pkg.mVersionCode);
8975                } else {
8976                    // The current app on the system partition is better than
8977                    // what we have updated to on the data partition; switch
8978                    // back to the system partition version.
8979                    // At this point, its safely assumed that package installation for
8980                    // apps in system partition will go through. If not there won't be a working
8981                    // version of the app
8982                    // writer
8983                    synchronized (mPackages) {
8984                        // Just remove the loaded entries from package lists.
8985                        mPackages.remove(ps.name);
8986                    }
8987
8988                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8989                            + " reverting from " + ps.codePathString
8990                            + ": new version " + pkg.mVersionCode
8991                            + " better than installed " + ps.versionCode);
8992
8993                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8994                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8995                    synchronized (mInstallLock) {
8996                        args.cleanUpResourcesLI();
8997                    }
8998                    synchronized (mPackages) {
8999                        mSettings.enableSystemPackageLPw(ps.name);
9000                    }
9001                    updatedPkgBetter = true;
9002                }
9003            }
9004        }
9005
9006        if (updatedPkg != null) {
9007            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9008            // initially
9009            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9010
9011            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9012            // flag set initially
9013            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9014                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9015            }
9016        }
9017
9018        // Verify certificates against what was last scanned
9019        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9020
9021        /*
9022         * A new system app appeared, but we already had a non-system one of the
9023         * same name installed earlier.
9024         */
9025        boolean shouldHideSystemApp = false;
9026        if (updatedPkg == null && ps != null
9027                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9028            /*
9029             * Check to make sure the signatures match first. If they don't,
9030             * wipe the installed application and its data.
9031             */
9032            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9033                    != PackageManager.SIGNATURE_MATCH) {
9034                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9035                        + " signatures don't match existing userdata copy; removing");
9036                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9037                        "scanPackageInternalLI")) {
9038                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9039                }
9040                ps = null;
9041            } else {
9042                /*
9043                 * If the newly-added system app is an older version than the
9044                 * already installed version, hide it. It will be scanned later
9045                 * and re-added like an update.
9046                 */
9047                if (pkg.mVersionCode <= ps.versionCode) {
9048                    shouldHideSystemApp = true;
9049                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9050                            + " but new version " + pkg.mVersionCode + " better than installed "
9051                            + ps.versionCode + "; hiding system");
9052                } else {
9053                    /*
9054                     * The newly found system app is a newer version that the
9055                     * one previously installed. Simply remove the
9056                     * already-installed application and replace it with our own
9057                     * while keeping the application data.
9058                     */
9059                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9060                            + " reverting from " + ps.codePathString + ": new version "
9061                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9062                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9063                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9064                    synchronized (mInstallLock) {
9065                        args.cleanUpResourcesLI();
9066                    }
9067                }
9068            }
9069        }
9070
9071        // The apk is forward locked (not public) if its code and resources
9072        // are kept in different files. (except for app in either system or
9073        // vendor path).
9074        // TODO grab this value from PackageSettings
9075        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9076            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9077                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9078            }
9079        }
9080
9081        // TODO: extend to support forward-locked splits
9082        String resourcePath = null;
9083        String baseResourcePath = null;
9084        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9085            if (ps != null && ps.resourcePathString != null) {
9086                resourcePath = ps.resourcePathString;
9087                baseResourcePath = ps.resourcePathString;
9088            } else {
9089                // Should not happen at all. Just log an error.
9090                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9091            }
9092        } else {
9093            resourcePath = pkg.codePath;
9094            baseResourcePath = pkg.baseCodePath;
9095        }
9096
9097        // Set application objects path explicitly.
9098        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9099        pkg.setApplicationInfoCodePath(pkg.codePath);
9100        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9101        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9102        pkg.setApplicationInfoResourcePath(resourcePath);
9103        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9104        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9105
9106        final int userId = ((user == null) ? 0 : user.getIdentifier());
9107        if (ps != null && ps.getInstantApp(userId)) {
9108            scanFlags |= SCAN_AS_INSTANT_APP;
9109        }
9110
9111        // Note that we invoke the following method only if we are about to unpack an application
9112        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9113                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9114
9115        /*
9116         * If the system app should be overridden by a previously installed
9117         * data, hide the system app now and let the /data/app scan pick it up
9118         * again.
9119         */
9120        if (shouldHideSystemApp) {
9121            synchronized (mPackages) {
9122                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9123            }
9124        }
9125
9126        return scannedPkg;
9127    }
9128
9129    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9130        // Derive the new package synthetic package name
9131        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9132                + pkg.staticSharedLibVersion);
9133    }
9134
9135    private static String fixProcessName(String defProcessName,
9136            String processName) {
9137        if (processName == null) {
9138            return defProcessName;
9139        }
9140        return processName;
9141    }
9142
9143    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9144            throws PackageManagerException {
9145        if (pkgSetting.signatures.mSignatures != null) {
9146            // Already existing package. Make sure signatures match
9147            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9148                    == PackageManager.SIGNATURE_MATCH;
9149            if (!match) {
9150                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9151                        == PackageManager.SIGNATURE_MATCH;
9152            }
9153            if (!match) {
9154                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9155                        == PackageManager.SIGNATURE_MATCH;
9156            }
9157            if (!match) {
9158                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9159                        + pkg.packageName + " signatures do not match the "
9160                        + "previously installed version; ignoring!");
9161            }
9162        }
9163
9164        // Check for shared user signatures
9165        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9166            // Already existing package. Make sure signatures match
9167            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9168                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9169            if (!match) {
9170                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9171                        == PackageManager.SIGNATURE_MATCH;
9172            }
9173            if (!match) {
9174                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9175                        == PackageManager.SIGNATURE_MATCH;
9176            }
9177            if (!match) {
9178                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9179                        "Package " + pkg.packageName
9180                        + " has no signatures that match those in shared user "
9181                        + pkgSetting.sharedUser.name + "; ignoring!");
9182            }
9183        }
9184    }
9185
9186    /**
9187     * Enforces that only the system UID or root's UID can call a method exposed
9188     * via Binder.
9189     *
9190     * @param message used as message if SecurityException is thrown
9191     * @throws SecurityException if the caller is not system or root
9192     */
9193    private static final void enforceSystemOrRoot(String message) {
9194        final int uid = Binder.getCallingUid();
9195        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9196            throw new SecurityException(message);
9197        }
9198    }
9199
9200    @Override
9201    public void performFstrimIfNeeded() {
9202        enforceSystemOrRoot("Only the system can request fstrim");
9203
9204        // Before everything else, see whether we need to fstrim.
9205        try {
9206            IStorageManager sm = PackageHelper.getStorageManager();
9207            if (sm != null) {
9208                boolean doTrim = false;
9209                final long interval = android.provider.Settings.Global.getLong(
9210                        mContext.getContentResolver(),
9211                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9212                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9213                if (interval > 0) {
9214                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9215                    if (timeSinceLast > interval) {
9216                        doTrim = true;
9217                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9218                                + "; running immediately");
9219                    }
9220                }
9221                if (doTrim) {
9222                    final boolean dexOptDialogShown;
9223                    synchronized (mPackages) {
9224                        dexOptDialogShown = mDexOptDialogShown;
9225                    }
9226                    if (!isFirstBoot() && dexOptDialogShown) {
9227                        try {
9228                            ActivityManager.getService().showBootMessage(
9229                                    mContext.getResources().getString(
9230                                            R.string.android_upgrading_fstrim), true);
9231                        } catch (RemoteException e) {
9232                        }
9233                    }
9234                    sm.runMaintenance();
9235                }
9236            } else {
9237                Slog.e(TAG, "storageManager service unavailable!");
9238            }
9239        } catch (RemoteException e) {
9240            // Can't happen; StorageManagerService is local
9241        }
9242    }
9243
9244    @Override
9245    public void updatePackagesIfNeeded() {
9246        enforceSystemOrRoot("Only the system can request package update");
9247
9248        // We need to re-extract after an OTA.
9249        boolean causeUpgrade = isUpgrade();
9250
9251        // First boot or factory reset.
9252        // Note: we also handle devices that are upgrading to N right now as if it is their
9253        //       first boot, as they do not have profile data.
9254        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9255
9256        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9257        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9258
9259        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9260            return;
9261        }
9262
9263        List<PackageParser.Package> pkgs;
9264        synchronized (mPackages) {
9265            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9266        }
9267
9268        final long startTime = System.nanoTime();
9269        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9270                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9271                    false /* bootComplete */);
9272
9273        final int elapsedTimeSeconds =
9274                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9275
9276        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9277        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9278        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9279        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9280        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9281    }
9282
9283    /**
9284     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9285     * containing statistics about the invocation. The array consists of three elements,
9286     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9287     * and {@code numberOfPackagesFailed}.
9288     */
9289    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9290            String compilerFilter, boolean bootComplete) {
9291
9292        int numberOfPackagesVisited = 0;
9293        int numberOfPackagesOptimized = 0;
9294        int numberOfPackagesSkipped = 0;
9295        int numberOfPackagesFailed = 0;
9296        final int numberOfPackagesToDexopt = pkgs.size();
9297
9298        for (PackageParser.Package pkg : pkgs) {
9299            numberOfPackagesVisited++;
9300
9301            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9302                if (DEBUG_DEXOPT) {
9303                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9304                }
9305                numberOfPackagesSkipped++;
9306                continue;
9307            }
9308
9309            if (DEBUG_DEXOPT) {
9310                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9311                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9312            }
9313
9314            if (showDialog) {
9315                try {
9316                    ActivityManager.getService().showBootMessage(
9317                            mContext.getResources().getString(R.string.android_upgrading_apk,
9318                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9319                } catch (RemoteException e) {
9320                }
9321                synchronized (mPackages) {
9322                    mDexOptDialogShown = true;
9323                }
9324            }
9325
9326            // If the OTA updates a system app which was previously preopted to a non-preopted state
9327            // the app might end up being verified at runtime. That's because by default the apps
9328            // are verify-profile but for preopted apps there's no profile.
9329            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9330            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9331            // filter (by default 'quicken').
9332            // Note that at this stage unused apps are already filtered.
9333            if (isSystemApp(pkg) &&
9334                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9335                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9336                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9337            }
9338
9339            // checkProfiles is false to avoid merging profiles during boot which
9340            // might interfere with background compilation (b/28612421).
9341            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9342            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9343            // trade-off worth doing to save boot time work.
9344            int dexOptStatus = performDexOptTraced(pkg.packageName,
9345                    false /* checkProfiles */,
9346                    compilerFilter,
9347                    false /* force */,
9348                    bootComplete);
9349            switch (dexOptStatus) {
9350                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9351                    numberOfPackagesOptimized++;
9352                    break;
9353                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9354                    numberOfPackagesSkipped++;
9355                    break;
9356                case PackageDexOptimizer.DEX_OPT_FAILED:
9357                    numberOfPackagesFailed++;
9358                    break;
9359                default:
9360                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9361                    break;
9362            }
9363        }
9364
9365        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9366                numberOfPackagesFailed };
9367    }
9368
9369    @Override
9370    public void notifyPackageUse(String packageName, int reason) {
9371        synchronized (mPackages) {
9372            final int callingUid = Binder.getCallingUid();
9373            final int callingUserId = UserHandle.getUserId(callingUid);
9374            if (getInstantAppPackageName(callingUid) != null) {
9375                if (!isCallerSameApp(packageName, callingUid)) {
9376                    return;
9377                }
9378            } else {
9379                if (isInstantApp(packageName, callingUserId)) {
9380                    return;
9381                }
9382            }
9383            final PackageParser.Package p = mPackages.get(packageName);
9384            if (p == null) {
9385                return;
9386            }
9387            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9388        }
9389    }
9390
9391    @Override
9392    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9393        int userId = UserHandle.getCallingUserId();
9394        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9395        if (ai == null) {
9396            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9397                + loadingPackageName + ", user=" + userId);
9398            return;
9399        }
9400        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9401    }
9402
9403    @Override
9404    public boolean performDexOpt(String packageName,
9405            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9406        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9407            return false;
9408        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9409            return false;
9410        }
9411        int dexoptStatus = performDexOptWithStatus(
9412              packageName, checkProfiles, compileReason, force, bootComplete);
9413        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9414    }
9415
9416    /**
9417     * Perform dexopt on the given package and return one of following result:
9418     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9419     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9420     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9421     */
9422    /* package */ int performDexOptWithStatus(String packageName,
9423            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9424        return performDexOptTraced(packageName, checkProfiles,
9425                getCompilerFilterForReason(compileReason), force, bootComplete);
9426    }
9427
9428    @Override
9429    public boolean performDexOptMode(String packageName,
9430            boolean checkProfiles, String targetCompilerFilter, boolean force,
9431            boolean bootComplete) {
9432        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9433            return false;
9434        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9435            return false;
9436        }
9437        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9438                targetCompilerFilter, force, bootComplete);
9439        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9440    }
9441
9442    private int performDexOptTraced(String packageName,
9443                boolean checkProfiles, String targetCompilerFilter, boolean force,
9444                boolean bootComplete) {
9445        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9446        try {
9447            return performDexOptInternal(packageName, checkProfiles,
9448                    targetCompilerFilter, force, bootComplete);
9449        } finally {
9450            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9451        }
9452    }
9453
9454    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9455    // if the package can now be considered up to date for the given filter.
9456    private int performDexOptInternal(String packageName,
9457                boolean checkProfiles, String targetCompilerFilter, boolean force,
9458                boolean bootComplete) {
9459        PackageParser.Package p;
9460        synchronized (mPackages) {
9461            p = mPackages.get(packageName);
9462            if (p == null) {
9463                // Package could not be found. Report failure.
9464                return PackageDexOptimizer.DEX_OPT_FAILED;
9465            }
9466            mPackageUsage.maybeWriteAsync(mPackages);
9467            mCompilerStats.maybeWriteAsync();
9468        }
9469        long callingId = Binder.clearCallingIdentity();
9470        try {
9471            synchronized (mInstallLock) {
9472                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9473                        targetCompilerFilter, force, bootComplete);
9474            }
9475        } finally {
9476            Binder.restoreCallingIdentity(callingId);
9477        }
9478    }
9479
9480    public ArraySet<String> getOptimizablePackages() {
9481        ArraySet<String> pkgs = new ArraySet<String>();
9482        synchronized (mPackages) {
9483            for (PackageParser.Package p : mPackages.values()) {
9484                if (PackageDexOptimizer.canOptimizePackage(p)) {
9485                    pkgs.add(p.packageName);
9486                }
9487            }
9488        }
9489        return pkgs;
9490    }
9491
9492    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9493            boolean checkProfiles, String targetCompilerFilter,
9494            boolean force, boolean bootComplete) {
9495        // Select the dex optimizer based on the force parameter.
9496        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9497        //       allocate an object here.
9498        PackageDexOptimizer pdo = force
9499                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9500                : mPackageDexOptimizer;
9501
9502        // Dexopt all dependencies first. Note: we ignore the return value and march on
9503        // on errors.
9504        // Note that we are going to call performDexOpt on those libraries as many times as
9505        // they are referenced in packages. When we do a batch of performDexOpt (for example
9506        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9507        // and the first package that uses the library will dexopt it. The
9508        // others will see that the compiled code for the library is up to date.
9509        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9510        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9511        if (!deps.isEmpty()) {
9512            for (PackageParser.Package depPackage : deps) {
9513                // TODO: Analyze and investigate if we (should) profile libraries.
9514                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9515                        false /* checkProfiles */,
9516                        targetCompilerFilter,
9517                        getOrCreateCompilerPackageStats(depPackage),
9518                        true /* isUsedByOtherApps */,
9519                        bootComplete);
9520            }
9521        }
9522        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9523                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9524                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9525    }
9526
9527    // Performs dexopt on the used secondary dex files belonging to the given package.
9528    // Returns true if all dex files were process successfully (which could mean either dexopt or
9529    // skip). Returns false if any of the files caused errors.
9530    @Override
9531    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9532            boolean force) {
9533        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9534            return false;
9535        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9536            return false;
9537        }
9538        mDexManager.reconcileSecondaryDexFiles(packageName);
9539        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9540    }
9541
9542    public boolean performDexOptSecondary(String packageName, int compileReason,
9543            boolean force) {
9544        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9545    }
9546
9547    /**
9548     * Reconcile the information we have about the secondary dex files belonging to
9549     * {@code packagName} and the actual dex files. For all dex files that were
9550     * deleted, update the internal records and delete the generated oat files.
9551     */
9552    @Override
9553    public void reconcileSecondaryDexFiles(String packageName) {
9554        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9555            return;
9556        }
9557        mDexManager.reconcileSecondaryDexFiles(packageName);
9558    }
9559
9560    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9561    // a reference there.
9562    /*package*/ DexManager getDexManager() {
9563        return mDexManager;
9564    }
9565
9566    /**
9567     * Execute the background dexopt job immediately.
9568     */
9569    @Override
9570    public boolean runBackgroundDexoptJob() {
9571        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9572            return false;
9573        }
9574        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9575    }
9576
9577    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9578        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9579                || p.usesStaticLibraries != null) {
9580            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9581            Set<String> collectedNames = new HashSet<>();
9582            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9583
9584            retValue.remove(p);
9585
9586            return retValue;
9587        } else {
9588            return Collections.emptyList();
9589        }
9590    }
9591
9592    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9593            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9594        if (!collectedNames.contains(p.packageName)) {
9595            collectedNames.add(p.packageName);
9596            collected.add(p);
9597
9598            if (p.usesLibraries != null) {
9599                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9600                        null, collected, collectedNames);
9601            }
9602            if (p.usesOptionalLibraries != null) {
9603                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9604                        null, collected, collectedNames);
9605            }
9606            if (p.usesStaticLibraries != null) {
9607                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9608                        p.usesStaticLibrariesVersions, collected, collectedNames);
9609            }
9610        }
9611    }
9612
9613    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9614            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9615        final int libNameCount = libs.size();
9616        for (int i = 0; i < libNameCount; i++) {
9617            String libName = libs.get(i);
9618            int version = (versions != null && versions.length == libNameCount)
9619                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9620            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9621            if (libPkg != null) {
9622                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9623            }
9624        }
9625    }
9626
9627    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9628        synchronized (mPackages) {
9629            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9630            if (libEntry != null) {
9631                return mPackages.get(libEntry.apk);
9632            }
9633            return null;
9634        }
9635    }
9636
9637    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9638        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9639        if (versionedLib == null) {
9640            return null;
9641        }
9642        return versionedLib.get(version);
9643    }
9644
9645    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9646        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9647                pkg.staticSharedLibName);
9648        if (versionedLib == null) {
9649            return null;
9650        }
9651        int previousLibVersion = -1;
9652        final int versionCount = versionedLib.size();
9653        for (int i = 0; i < versionCount; i++) {
9654            final int libVersion = versionedLib.keyAt(i);
9655            if (libVersion < pkg.staticSharedLibVersion) {
9656                previousLibVersion = Math.max(previousLibVersion, libVersion);
9657            }
9658        }
9659        if (previousLibVersion >= 0) {
9660            return versionedLib.get(previousLibVersion);
9661        }
9662        return null;
9663    }
9664
9665    public void shutdown() {
9666        mPackageUsage.writeNow(mPackages);
9667        mCompilerStats.writeNow();
9668    }
9669
9670    @Override
9671    public void dumpProfiles(String packageName) {
9672        PackageParser.Package pkg;
9673        synchronized (mPackages) {
9674            pkg = mPackages.get(packageName);
9675            if (pkg == null) {
9676                throw new IllegalArgumentException("Unknown package: " + packageName);
9677            }
9678        }
9679        /* Only the shell, root, or the app user should be able to dump profiles. */
9680        int callingUid = Binder.getCallingUid();
9681        if (callingUid != Process.SHELL_UID &&
9682            callingUid != Process.ROOT_UID &&
9683            callingUid != pkg.applicationInfo.uid) {
9684            throw new SecurityException("dumpProfiles");
9685        }
9686
9687        synchronized (mInstallLock) {
9688            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9689            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9690            try {
9691                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9692                String codePaths = TextUtils.join(";", allCodePaths);
9693                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9694            } catch (InstallerException e) {
9695                Slog.w(TAG, "Failed to dump profiles", e);
9696            }
9697            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9698        }
9699    }
9700
9701    @Override
9702    public void forceDexOpt(String packageName) {
9703        enforceSystemOrRoot("forceDexOpt");
9704
9705        PackageParser.Package pkg;
9706        synchronized (mPackages) {
9707            pkg = mPackages.get(packageName);
9708            if (pkg == null) {
9709                throw new IllegalArgumentException("Unknown package: " + packageName);
9710            }
9711        }
9712
9713        synchronized (mInstallLock) {
9714            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9715
9716            // Whoever is calling forceDexOpt wants a compiled package.
9717            // Don't use profiles since that may cause compilation to be skipped.
9718            final int res = performDexOptInternalWithDependenciesLI(pkg,
9719                    false /* checkProfiles */, getDefaultCompilerFilter(),
9720                    true /* force */,
9721                    true /* bootComplete */);
9722
9723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9724            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9725                throw new IllegalStateException("Failed to dexopt: " + res);
9726            }
9727        }
9728    }
9729
9730    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9731        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9732            Slog.w(TAG, "Unable to update from " + oldPkg.name
9733                    + " to " + newPkg.packageName
9734                    + ": old package not in system partition");
9735            return false;
9736        } else if (mPackages.get(oldPkg.name) != null) {
9737            Slog.w(TAG, "Unable to update from " + oldPkg.name
9738                    + " to " + newPkg.packageName
9739                    + ": old package still exists");
9740            return false;
9741        }
9742        return true;
9743    }
9744
9745    void removeCodePathLI(File codePath) {
9746        if (codePath.isDirectory()) {
9747            try {
9748                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9749            } catch (InstallerException e) {
9750                Slog.w(TAG, "Failed to remove code path", e);
9751            }
9752        } else {
9753            codePath.delete();
9754        }
9755    }
9756
9757    private int[] resolveUserIds(int userId) {
9758        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9759    }
9760
9761    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9762        if (pkg == null) {
9763            Slog.wtf(TAG, "Package was null!", new Throwable());
9764            return;
9765        }
9766        clearAppDataLeafLIF(pkg, userId, flags);
9767        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9768        for (int i = 0; i < childCount; i++) {
9769            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9770        }
9771    }
9772
9773    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9774        final PackageSetting ps;
9775        synchronized (mPackages) {
9776            ps = mSettings.mPackages.get(pkg.packageName);
9777        }
9778        for (int realUserId : resolveUserIds(userId)) {
9779            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9780            try {
9781                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9782                        ceDataInode);
9783            } catch (InstallerException e) {
9784                Slog.w(TAG, String.valueOf(e));
9785            }
9786        }
9787    }
9788
9789    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9790        if (pkg == null) {
9791            Slog.wtf(TAG, "Package was null!", new Throwable());
9792            return;
9793        }
9794        destroyAppDataLeafLIF(pkg, userId, flags);
9795        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9796        for (int i = 0; i < childCount; i++) {
9797            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9798        }
9799    }
9800
9801    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9802        final PackageSetting ps;
9803        synchronized (mPackages) {
9804            ps = mSettings.mPackages.get(pkg.packageName);
9805        }
9806        for (int realUserId : resolveUserIds(userId)) {
9807            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9808            try {
9809                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9810                        ceDataInode);
9811            } catch (InstallerException e) {
9812                Slog.w(TAG, String.valueOf(e));
9813            }
9814            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9815        }
9816    }
9817
9818    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9819        if (pkg == null) {
9820            Slog.wtf(TAG, "Package was null!", new Throwable());
9821            return;
9822        }
9823        destroyAppProfilesLeafLIF(pkg);
9824        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9825        for (int i = 0; i < childCount; i++) {
9826            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9827        }
9828    }
9829
9830    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9831        try {
9832            mInstaller.destroyAppProfiles(pkg.packageName);
9833        } catch (InstallerException e) {
9834            Slog.w(TAG, String.valueOf(e));
9835        }
9836    }
9837
9838    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9839        if (pkg == null) {
9840            Slog.wtf(TAG, "Package was null!", new Throwable());
9841            return;
9842        }
9843        clearAppProfilesLeafLIF(pkg);
9844        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9845        for (int i = 0; i < childCount; i++) {
9846            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9847        }
9848    }
9849
9850    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9851        try {
9852            mInstaller.clearAppProfiles(pkg.packageName);
9853        } catch (InstallerException e) {
9854            Slog.w(TAG, String.valueOf(e));
9855        }
9856    }
9857
9858    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9859            long lastUpdateTime) {
9860        // Set parent install/update time
9861        PackageSetting ps = (PackageSetting) pkg.mExtras;
9862        if (ps != null) {
9863            ps.firstInstallTime = firstInstallTime;
9864            ps.lastUpdateTime = lastUpdateTime;
9865        }
9866        // Set children install/update time
9867        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9868        for (int i = 0; i < childCount; i++) {
9869            PackageParser.Package childPkg = pkg.childPackages.get(i);
9870            ps = (PackageSetting) childPkg.mExtras;
9871            if (ps != null) {
9872                ps.firstInstallTime = firstInstallTime;
9873                ps.lastUpdateTime = lastUpdateTime;
9874            }
9875        }
9876    }
9877
9878    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9879            PackageParser.Package changingLib) {
9880        if (file.path != null) {
9881            usesLibraryFiles.add(file.path);
9882            return;
9883        }
9884        PackageParser.Package p = mPackages.get(file.apk);
9885        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9886            // If we are doing this while in the middle of updating a library apk,
9887            // then we need to make sure to use that new apk for determining the
9888            // dependencies here.  (We haven't yet finished committing the new apk
9889            // to the package manager state.)
9890            if (p == null || p.packageName.equals(changingLib.packageName)) {
9891                p = changingLib;
9892            }
9893        }
9894        if (p != null) {
9895            usesLibraryFiles.addAll(p.getAllCodePaths());
9896            if (p.usesLibraryFiles != null) {
9897                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9898            }
9899        }
9900    }
9901
9902    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9903            PackageParser.Package changingLib) throws PackageManagerException {
9904        if (pkg == null) {
9905            return;
9906        }
9907        ArraySet<String> usesLibraryFiles = null;
9908        if (pkg.usesLibraries != null) {
9909            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9910                    null, null, pkg.packageName, changingLib, true, null);
9911        }
9912        if (pkg.usesStaticLibraries != null) {
9913            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9914                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9915                    pkg.packageName, changingLib, true, usesLibraryFiles);
9916        }
9917        if (pkg.usesOptionalLibraries != null) {
9918            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9919                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9920        }
9921        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9922            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9923        } else {
9924            pkg.usesLibraryFiles = null;
9925        }
9926    }
9927
9928    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9929            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9930            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9931            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9932            throws PackageManagerException {
9933        final int libCount = requestedLibraries.size();
9934        for (int i = 0; i < libCount; i++) {
9935            final String libName = requestedLibraries.get(i);
9936            final int libVersion = requiredVersions != null ? requiredVersions[i]
9937                    : SharedLibraryInfo.VERSION_UNDEFINED;
9938            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9939            if (libEntry == null) {
9940                if (required) {
9941                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9942                            "Package " + packageName + " requires unavailable shared library "
9943                                    + libName + "; failing!");
9944                } else if (DEBUG_SHARED_LIBRARIES) {
9945                    Slog.i(TAG, "Package " + packageName
9946                            + " desires unavailable shared library "
9947                            + libName + "; ignoring!");
9948                }
9949            } else {
9950                if (requiredVersions != null && requiredCertDigests != null) {
9951                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9952                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9953                            "Package " + packageName + " requires unavailable static shared"
9954                                    + " library " + libName + " version "
9955                                    + libEntry.info.getVersion() + "; failing!");
9956                    }
9957
9958                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9959                    if (libPkg == null) {
9960                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9961                                "Package " + packageName + " requires unavailable static shared"
9962                                        + " library; failing!");
9963                    }
9964
9965                    String expectedCertDigest = requiredCertDigests[i];
9966                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9967                                libPkg.mSignatures[0]);
9968                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9969                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9970                                "Package " + packageName + " requires differently signed" +
9971                                        " static shared library; failing!");
9972                    }
9973                }
9974
9975                if (outUsedLibraries == null) {
9976                    outUsedLibraries = new ArraySet<>();
9977                }
9978                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9979            }
9980        }
9981        return outUsedLibraries;
9982    }
9983
9984    private static boolean hasString(List<String> list, List<String> which) {
9985        if (list == null) {
9986            return false;
9987        }
9988        for (int i=list.size()-1; i>=0; i--) {
9989            for (int j=which.size()-1; j>=0; j--) {
9990                if (which.get(j).equals(list.get(i))) {
9991                    return true;
9992                }
9993            }
9994        }
9995        return false;
9996    }
9997
9998    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9999            PackageParser.Package changingPkg) {
10000        ArrayList<PackageParser.Package> res = null;
10001        for (PackageParser.Package pkg : mPackages.values()) {
10002            if (changingPkg != null
10003                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10004                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10005                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10006                            changingPkg.staticSharedLibName)) {
10007                return null;
10008            }
10009            if (res == null) {
10010                res = new ArrayList<>();
10011            }
10012            res.add(pkg);
10013            try {
10014                updateSharedLibrariesLPr(pkg, changingPkg);
10015            } catch (PackageManagerException e) {
10016                // If a system app update or an app and a required lib missing we
10017                // delete the package and for updated system apps keep the data as
10018                // it is better for the user to reinstall than to be in an limbo
10019                // state. Also libs disappearing under an app should never happen
10020                // - just in case.
10021                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10022                    final int flags = pkg.isUpdatedSystemApp()
10023                            ? PackageManager.DELETE_KEEP_DATA : 0;
10024                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10025                            flags , null, true, null);
10026                }
10027                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10028            }
10029        }
10030        return res;
10031    }
10032
10033    /**
10034     * Derive the value of the {@code cpuAbiOverride} based on the provided
10035     * value and an optional stored value from the package settings.
10036     */
10037    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10038        String cpuAbiOverride = null;
10039
10040        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10041            cpuAbiOverride = null;
10042        } else if (abiOverride != null) {
10043            cpuAbiOverride = abiOverride;
10044        } else if (settings != null) {
10045            cpuAbiOverride = settings.cpuAbiOverrideString;
10046        }
10047
10048        return cpuAbiOverride;
10049    }
10050
10051    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10052            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10053                    throws PackageManagerException {
10054        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10055        // If the package has children and this is the first dive in the function
10056        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10057        // whether all packages (parent and children) would be successfully scanned
10058        // before the actual scan since scanning mutates internal state and we want
10059        // to atomically install the package and its children.
10060        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10061            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10062                scanFlags |= SCAN_CHECK_ONLY;
10063            }
10064        } else {
10065            scanFlags &= ~SCAN_CHECK_ONLY;
10066        }
10067
10068        final PackageParser.Package scannedPkg;
10069        try {
10070            // Scan the parent
10071            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10072            // Scan the children
10073            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10074            for (int i = 0; i < childCount; i++) {
10075                PackageParser.Package childPkg = pkg.childPackages.get(i);
10076                scanPackageLI(childPkg, policyFlags,
10077                        scanFlags, currentTime, user);
10078            }
10079        } finally {
10080            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10081        }
10082
10083        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10084            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10085        }
10086
10087        return scannedPkg;
10088    }
10089
10090    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10091            int scanFlags, long currentTime, @Nullable UserHandle user)
10092                    throws PackageManagerException {
10093        boolean success = false;
10094        try {
10095            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10096                    currentTime, user);
10097            success = true;
10098            return res;
10099        } finally {
10100            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10101                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10102                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10103                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10104                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10105            }
10106        }
10107    }
10108
10109    /**
10110     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10111     */
10112    private static boolean apkHasCode(String fileName) {
10113        StrictJarFile jarFile = null;
10114        try {
10115            jarFile = new StrictJarFile(fileName,
10116                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10117            return jarFile.findEntry("classes.dex") != null;
10118        } catch (IOException ignore) {
10119        } finally {
10120            try {
10121                if (jarFile != null) {
10122                    jarFile.close();
10123                }
10124            } catch (IOException ignore) {}
10125        }
10126        return false;
10127    }
10128
10129    /**
10130     * Enforces code policy for the package. This ensures that if an APK has
10131     * declared hasCode="true" in its manifest that the APK actually contains
10132     * code.
10133     *
10134     * @throws PackageManagerException If bytecode could not be found when it should exist
10135     */
10136    private static void assertCodePolicy(PackageParser.Package pkg)
10137            throws PackageManagerException {
10138        final boolean shouldHaveCode =
10139                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10140        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10141            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10142                    "Package " + pkg.baseCodePath + " code is missing");
10143        }
10144
10145        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10146            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10147                final boolean splitShouldHaveCode =
10148                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10149                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10150                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10151                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10152                }
10153            }
10154        }
10155    }
10156
10157    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10158            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10159                    throws PackageManagerException {
10160        if (DEBUG_PACKAGE_SCANNING) {
10161            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10162                Log.d(TAG, "Scanning package " + pkg.packageName);
10163        }
10164
10165        applyPolicy(pkg, policyFlags);
10166
10167        assertPackageIsValid(pkg, policyFlags, scanFlags);
10168
10169        // Initialize package source and resource directories
10170        final File scanFile = new File(pkg.codePath);
10171        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10172        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10173
10174        SharedUserSetting suid = null;
10175        PackageSetting pkgSetting = null;
10176
10177        // Getting the package setting may have a side-effect, so if we
10178        // are only checking if scan would succeed, stash a copy of the
10179        // old setting to restore at the end.
10180        PackageSetting nonMutatedPs = null;
10181
10182        // We keep references to the derived CPU Abis from settings in oder to reuse
10183        // them in the case where we're not upgrading or booting for the first time.
10184        String primaryCpuAbiFromSettings = null;
10185        String secondaryCpuAbiFromSettings = null;
10186
10187        // writer
10188        synchronized (mPackages) {
10189            if (pkg.mSharedUserId != null) {
10190                // SIDE EFFECTS; may potentially allocate a new shared user
10191                suid = mSettings.getSharedUserLPw(
10192                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10193                if (DEBUG_PACKAGE_SCANNING) {
10194                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10195                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10196                                + "): packages=" + suid.packages);
10197                }
10198            }
10199
10200            // Check if we are renaming from an original package name.
10201            PackageSetting origPackage = null;
10202            String realName = null;
10203            if (pkg.mOriginalPackages != null) {
10204                // This package may need to be renamed to a previously
10205                // installed name.  Let's check on that...
10206                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10207                if (pkg.mOriginalPackages.contains(renamed)) {
10208                    // This package had originally been installed as the
10209                    // original name, and we have already taken care of
10210                    // transitioning to the new one.  Just update the new
10211                    // one to continue using the old name.
10212                    realName = pkg.mRealPackage;
10213                    if (!pkg.packageName.equals(renamed)) {
10214                        // Callers into this function may have already taken
10215                        // care of renaming the package; only do it here if
10216                        // it is not already done.
10217                        pkg.setPackageName(renamed);
10218                    }
10219                } else {
10220                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10221                        if ((origPackage = mSettings.getPackageLPr(
10222                                pkg.mOriginalPackages.get(i))) != null) {
10223                            // We do have the package already installed under its
10224                            // original name...  should we use it?
10225                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10226                                // New package is not compatible with original.
10227                                origPackage = null;
10228                                continue;
10229                            } else if (origPackage.sharedUser != null) {
10230                                // Make sure uid is compatible between packages.
10231                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10232                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10233                                            + " to " + pkg.packageName + ": old uid "
10234                                            + origPackage.sharedUser.name
10235                                            + " differs from " + pkg.mSharedUserId);
10236                                    origPackage = null;
10237                                    continue;
10238                                }
10239                                // TODO: Add case when shared user id is added [b/28144775]
10240                            } else {
10241                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10242                                        + pkg.packageName + " to old name " + origPackage.name);
10243                            }
10244                            break;
10245                        }
10246                    }
10247                }
10248            }
10249
10250            if (mTransferedPackages.contains(pkg.packageName)) {
10251                Slog.w(TAG, "Package " + pkg.packageName
10252                        + " was transferred to another, but its .apk remains");
10253            }
10254
10255            // See comments in nonMutatedPs declaration
10256            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10257                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10258                if (foundPs != null) {
10259                    nonMutatedPs = new PackageSetting(foundPs);
10260                }
10261            }
10262
10263            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10264                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10265                if (foundPs != null) {
10266                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10267                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10268                }
10269            }
10270
10271            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10272            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10273                PackageManagerService.reportSettingsProblem(Log.WARN,
10274                        "Package " + pkg.packageName + " shared user changed from "
10275                                + (pkgSetting.sharedUser != null
10276                                        ? pkgSetting.sharedUser.name : "<nothing>")
10277                                + " to "
10278                                + (suid != null ? suid.name : "<nothing>")
10279                                + "; replacing with new");
10280                pkgSetting = null;
10281            }
10282            final PackageSetting oldPkgSetting =
10283                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10284            final PackageSetting disabledPkgSetting =
10285                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10286
10287            String[] usesStaticLibraries = null;
10288            if (pkg.usesStaticLibraries != null) {
10289                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10290                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10291            }
10292
10293            if (pkgSetting == null) {
10294                final String parentPackageName = (pkg.parentPackage != null)
10295                        ? pkg.parentPackage.packageName : null;
10296                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10297                // REMOVE SharedUserSetting from method; update in a separate call
10298                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10299                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10300                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10301                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10302                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10303                        true /*allowInstall*/, instantApp, parentPackageName,
10304                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10305                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10306                // SIDE EFFECTS; updates system state; move elsewhere
10307                if (origPackage != null) {
10308                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10309                }
10310                mSettings.addUserToSettingLPw(pkgSetting);
10311            } else {
10312                // REMOVE SharedUserSetting from method; update in a separate call.
10313                //
10314                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10315                // secondaryCpuAbi are not known at this point so we always update them
10316                // to null here, only to reset them at a later point.
10317                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10318                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10319                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10320                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10321                        UserManagerService.getInstance(), usesStaticLibraries,
10322                        pkg.usesStaticLibrariesVersions);
10323            }
10324            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10325            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10326
10327            // SIDE EFFECTS; modifies system state; move elsewhere
10328            if (pkgSetting.origPackage != null) {
10329                // If we are first transitioning from an original package,
10330                // fix up the new package's name now.  We need to do this after
10331                // looking up the package under its new name, so getPackageLP
10332                // can take care of fiddling things correctly.
10333                pkg.setPackageName(origPackage.name);
10334
10335                // File a report about this.
10336                String msg = "New package " + pkgSetting.realName
10337                        + " renamed to replace old package " + pkgSetting.name;
10338                reportSettingsProblem(Log.WARN, msg);
10339
10340                // Make a note of it.
10341                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10342                    mTransferedPackages.add(origPackage.name);
10343                }
10344
10345                // No longer need to retain this.
10346                pkgSetting.origPackage = null;
10347            }
10348
10349            // SIDE EFFECTS; modifies system state; move elsewhere
10350            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10351                // Make a note of it.
10352                mTransferedPackages.add(pkg.packageName);
10353            }
10354
10355            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10356                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10357            }
10358
10359            if ((scanFlags & SCAN_BOOTING) == 0
10360                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10361                // Check all shared libraries and map to their actual file path.
10362                // We only do this here for apps not on a system dir, because those
10363                // are the only ones that can fail an install due to this.  We
10364                // will take care of the system apps by updating all of their
10365                // library paths after the scan is done. Also during the initial
10366                // scan don't update any libs as we do this wholesale after all
10367                // apps are scanned to avoid dependency based scanning.
10368                updateSharedLibrariesLPr(pkg, null);
10369            }
10370
10371            if (mFoundPolicyFile) {
10372                SELinuxMMAC.assignSeInfoValue(pkg);
10373            }
10374            pkg.applicationInfo.uid = pkgSetting.appId;
10375            pkg.mExtras = pkgSetting;
10376
10377
10378            // Static shared libs have same package with different versions where
10379            // we internally use a synthetic package name to allow multiple versions
10380            // of the same package, therefore we need to compare signatures against
10381            // the package setting for the latest library version.
10382            PackageSetting signatureCheckPs = pkgSetting;
10383            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10384                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10385                if (libraryEntry != null) {
10386                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10387                }
10388            }
10389
10390            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10391                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10392                    // We just determined the app is signed correctly, so bring
10393                    // over the latest parsed certs.
10394                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10395                } else {
10396                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10397                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10398                                "Package " + pkg.packageName + " upgrade keys do not match the "
10399                                + "previously installed version");
10400                    } else {
10401                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10402                        String msg = "System package " + pkg.packageName
10403                                + " signature changed; retaining data.";
10404                        reportSettingsProblem(Log.WARN, msg);
10405                    }
10406                }
10407            } else {
10408                try {
10409                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10410                    verifySignaturesLP(signatureCheckPs, pkg);
10411                    // We just determined the app is signed correctly, so bring
10412                    // over the latest parsed certs.
10413                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10414                } catch (PackageManagerException e) {
10415                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10416                        throw e;
10417                    }
10418                    // The signature has changed, but this package is in the system
10419                    // image...  let's recover!
10420                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10421                    // However...  if this package is part of a shared user, but it
10422                    // doesn't match the signature of the shared user, let's fail.
10423                    // What this means is that you can't change the signatures
10424                    // associated with an overall shared user, which doesn't seem all
10425                    // that unreasonable.
10426                    if (signatureCheckPs.sharedUser != null) {
10427                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10428                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10429                            throw new PackageManagerException(
10430                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10431                                    "Signature mismatch for shared user: "
10432                                            + pkgSetting.sharedUser);
10433                        }
10434                    }
10435                    // File a report about this.
10436                    String msg = "System package " + pkg.packageName
10437                            + " signature changed; retaining data.";
10438                    reportSettingsProblem(Log.WARN, msg);
10439                }
10440            }
10441
10442            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10443                // This package wants to adopt ownership of permissions from
10444                // another package.
10445                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10446                    final String origName = pkg.mAdoptPermissions.get(i);
10447                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10448                    if (orig != null) {
10449                        if (verifyPackageUpdateLPr(orig, pkg)) {
10450                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10451                                    + pkg.packageName);
10452                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10453                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10454                        }
10455                    }
10456                }
10457            }
10458        }
10459
10460        pkg.applicationInfo.processName = fixProcessName(
10461                pkg.applicationInfo.packageName,
10462                pkg.applicationInfo.processName);
10463
10464        if (pkg != mPlatformPackage) {
10465            // Get all of our default paths setup
10466            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10467        }
10468
10469        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10470
10471        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10472            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10473                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10474                derivePackageAbi(
10475                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
10476                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10477
10478                // Some system apps still use directory structure for native libraries
10479                // in which case we might end up not detecting abi solely based on apk
10480                // structure. Try to detect abi based on directory structure.
10481                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10482                        pkg.applicationInfo.primaryCpuAbi == null) {
10483                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10484                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10485                }
10486            } else {
10487                // This is not a first boot or an upgrade, don't bother deriving the
10488                // ABI during the scan. Instead, trust the value that was stored in the
10489                // package setting.
10490                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10491                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10492
10493                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10494
10495                if (DEBUG_ABI_SELECTION) {
10496                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10497                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10498                        pkg.applicationInfo.secondaryCpuAbi);
10499                }
10500            }
10501        } else {
10502            if ((scanFlags & SCAN_MOVE) != 0) {
10503                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10504                // but we already have this packages package info in the PackageSetting. We just
10505                // use that and derive the native library path based on the new codepath.
10506                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10507                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10508            }
10509
10510            // Set native library paths again. For moves, the path will be updated based on the
10511            // ABIs we've determined above. For non-moves, the path will be updated based on the
10512            // ABIs we determined during compilation, but the path will depend on the final
10513            // package path (after the rename away from the stage path).
10514            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10515        }
10516
10517        // This is a special case for the "system" package, where the ABI is
10518        // dictated by the zygote configuration (and init.rc). We should keep track
10519        // of this ABI so that we can deal with "normal" applications that run under
10520        // the same UID correctly.
10521        if (mPlatformPackage == pkg) {
10522            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10523                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10524        }
10525
10526        // If there's a mismatch between the abi-override in the package setting
10527        // and the abiOverride specified for the install. Warn about this because we
10528        // would've already compiled the app without taking the package setting into
10529        // account.
10530        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10531            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10532                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10533                        " for package " + pkg.packageName);
10534            }
10535        }
10536
10537        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10538        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10539        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10540
10541        // Copy the derived override back to the parsed package, so that we can
10542        // update the package settings accordingly.
10543        pkg.cpuAbiOverride = cpuAbiOverride;
10544
10545        if (DEBUG_ABI_SELECTION) {
10546            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10547                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10548                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10549        }
10550
10551        // Push the derived path down into PackageSettings so we know what to
10552        // clean up at uninstall time.
10553        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10554
10555        if (DEBUG_ABI_SELECTION) {
10556            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10557                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10558                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10559        }
10560
10561        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10562        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10563            // We don't do this here during boot because we can do it all
10564            // at once after scanning all existing packages.
10565            //
10566            // We also do this *before* we perform dexopt on this package, so that
10567            // we can avoid redundant dexopts, and also to make sure we've got the
10568            // code and package path correct.
10569            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10570        }
10571
10572        if (mFactoryTest && pkg.requestedPermissions.contains(
10573                android.Manifest.permission.FACTORY_TEST)) {
10574            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10575        }
10576
10577        if (isSystemApp(pkg)) {
10578            pkgSetting.isOrphaned = true;
10579        }
10580
10581        // Take care of first install / last update times.
10582        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10583        if (currentTime != 0) {
10584            if (pkgSetting.firstInstallTime == 0) {
10585                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10586            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10587                pkgSetting.lastUpdateTime = currentTime;
10588            }
10589        } else if (pkgSetting.firstInstallTime == 0) {
10590            // We need *something*.  Take time time stamp of the file.
10591            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10592        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10593            if (scanFileTime != pkgSetting.timeStamp) {
10594                // A package on the system image has changed; consider this
10595                // to be an update.
10596                pkgSetting.lastUpdateTime = scanFileTime;
10597            }
10598        }
10599        pkgSetting.setTimeStamp(scanFileTime);
10600
10601        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10602            if (nonMutatedPs != null) {
10603                synchronized (mPackages) {
10604                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10605                }
10606            }
10607        } else {
10608            final int userId = user == null ? 0 : user.getIdentifier();
10609            // Modify state for the given package setting
10610            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10611                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10612            if (pkgSetting.getInstantApp(userId)) {
10613                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10614            }
10615        }
10616        return pkg;
10617    }
10618
10619    /**
10620     * Applies policy to the parsed package based upon the given policy flags.
10621     * Ensures the package is in a good state.
10622     * <p>
10623     * Implementation detail: This method must NOT have any side effect. It would
10624     * ideally be static, but, it requires locks to read system state.
10625     */
10626    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10627        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10628            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10629            if (pkg.applicationInfo.isDirectBootAware()) {
10630                // we're direct boot aware; set for all components
10631                for (PackageParser.Service s : pkg.services) {
10632                    s.info.encryptionAware = s.info.directBootAware = true;
10633                }
10634                for (PackageParser.Provider p : pkg.providers) {
10635                    p.info.encryptionAware = p.info.directBootAware = true;
10636                }
10637                for (PackageParser.Activity a : pkg.activities) {
10638                    a.info.encryptionAware = a.info.directBootAware = true;
10639                }
10640                for (PackageParser.Activity r : pkg.receivers) {
10641                    r.info.encryptionAware = r.info.directBootAware = true;
10642                }
10643            }
10644        } else {
10645            // Only allow system apps to be flagged as core apps.
10646            pkg.coreApp = false;
10647            // clear flags not applicable to regular apps
10648            pkg.applicationInfo.privateFlags &=
10649                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10650            pkg.applicationInfo.privateFlags &=
10651                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10652        }
10653        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10654
10655        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10656            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10657        }
10658
10659        if (!isSystemApp(pkg)) {
10660            // Only system apps can use these features.
10661            pkg.mOriginalPackages = null;
10662            pkg.mRealPackage = null;
10663            pkg.mAdoptPermissions = null;
10664        }
10665    }
10666
10667    /**
10668     * Asserts the parsed package is valid according to the given policy. If the
10669     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10670     * <p>
10671     * Implementation detail: This method must NOT have any side effects. It would
10672     * ideally be static, but, it requires locks to read system state.
10673     *
10674     * @throws PackageManagerException If the package fails any of the validation checks
10675     */
10676    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10677            throws PackageManagerException {
10678        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10679            assertCodePolicy(pkg);
10680        }
10681
10682        if (pkg.applicationInfo.getCodePath() == null ||
10683                pkg.applicationInfo.getResourcePath() == null) {
10684            // Bail out. The resource and code paths haven't been set.
10685            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10686                    "Code and resource paths haven't been set correctly");
10687        }
10688
10689        // Make sure we're not adding any bogus keyset info
10690        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10691        ksms.assertScannedPackageValid(pkg);
10692
10693        synchronized (mPackages) {
10694            // The special "android" package can only be defined once
10695            if (pkg.packageName.equals("android")) {
10696                if (mAndroidApplication != null) {
10697                    Slog.w(TAG, "*************************************************");
10698                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10699                    Slog.w(TAG, " codePath=" + pkg.codePath);
10700                    Slog.w(TAG, "*************************************************");
10701                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10702                            "Core android package being redefined.  Skipping.");
10703                }
10704            }
10705
10706            // A package name must be unique; don't allow duplicates
10707            if (mPackages.containsKey(pkg.packageName)) {
10708                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10709                        "Application package " + pkg.packageName
10710                        + " already installed.  Skipping duplicate.");
10711            }
10712
10713            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10714                // Static libs have a synthetic package name containing the version
10715                // but we still want the base name to be unique.
10716                if (mPackages.containsKey(pkg.manifestPackageName)) {
10717                    throw new PackageManagerException(
10718                            "Duplicate static shared lib provider package");
10719                }
10720
10721                // Static shared libraries should have at least O target SDK
10722                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10723                    throw new PackageManagerException(
10724                            "Packages declaring static-shared libs must target O SDK or higher");
10725                }
10726
10727                // Package declaring static a shared lib cannot be instant apps
10728                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10729                    throw new PackageManagerException(
10730                            "Packages declaring static-shared libs cannot be instant apps");
10731                }
10732
10733                // Package declaring static a shared lib cannot be renamed since the package
10734                // name is synthetic and apps can't code around package manager internals.
10735                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10736                    throw new PackageManagerException(
10737                            "Packages declaring static-shared libs cannot be renamed");
10738                }
10739
10740                // Package declaring static a shared lib cannot declare child packages
10741                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10742                    throw new PackageManagerException(
10743                            "Packages declaring static-shared libs cannot have child packages");
10744                }
10745
10746                // Package declaring static a shared lib cannot declare dynamic libs
10747                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10748                    throw new PackageManagerException(
10749                            "Packages declaring static-shared libs cannot declare dynamic libs");
10750                }
10751
10752                // Package declaring static a shared lib cannot declare shared users
10753                if (pkg.mSharedUserId != null) {
10754                    throw new PackageManagerException(
10755                            "Packages declaring static-shared libs cannot declare shared users");
10756                }
10757
10758                // Static shared libs cannot declare activities
10759                if (!pkg.activities.isEmpty()) {
10760                    throw new PackageManagerException(
10761                            "Static shared libs cannot declare activities");
10762                }
10763
10764                // Static shared libs cannot declare services
10765                if (!pkg.services.isEmpty()) {
10766                    throw new PackageManagerException(
10767                            "Static shared libs cannot declare services");
10768                }
10769
10770                // Static shared libs cannot declare providers
10771                if (!pkg.providers.isEmpty()) {
10772                    throw new PackageManagerException(
10773                            "Static shared libs cannot declare content providers");
10774                }
10775
10776                // Static shared libs cannot declare receivers
10777                if (!pkg.receivers.isEmpty()) {
10778                    throw new PackageManagerException(
10779                            "Static shared libs cannot declare broadcast receivers");
10780                }
10781
10782                // Static shared libs cannot declare permission groups
10783                if (!pkg.permissionGroups.isEmpty()) {
10784                    throw new PackageManagerException(
10785                            "Static shared libs cannot declare permission groups");
10786                }
10787
10788                // Static shared libs cannot declare permissions
10789                if (!pkg.permissions.isEmpty()) {
10790                    throw new PackageManagerException(
10791                            "Static shared libs cannot declare permissions");
10792                }
10793
10794                // Static shared libs cannot declare protected broadcasts
10795                if (pkg.protectedBroadcasts != null) {
10796                    throw new PackageManagerException(
10797                            "Static shared libs cannot declare protected broadcasts");
10798                }
10799
10800                // Static shared libs cannot be overlay targets
10801                if (pkg.mOverlayTarget != null) {
10802                    throw new PackageManagerException(
10803                            "Static shared libs cannot be overlay targets");
10804                }
10805
10806                // The version codes must be ordered as lib versions
10807                int minVersionCode = Integer.MIN_VALUE;
10808                int maxVersionCode = Integer.MAX_VALUE;
10809
10810                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10811                        pkg.staticSharedLibName);
10812                if (versionedLib != null) {
10813                    final int versionCount = versionedLib.size();
10814                    for (int i = 0; i < versionCount; i++) {
10815                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10816                        final int libVersionCode = libInfo.getDeclaringPackage()
10817                                .getVersionCode();
10818                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10819                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10820                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10821                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10822                        } else {
10823                            minVersionCode = maxVersionCode = libVersionCode;
10824                            break;
10825                        }
10826                    }
10827                }
10828                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10829                    throw new PackageManagerException("Static shared"
10830                            + " lib version codes must be ordered as lib versions");
10831                }
10832            }
10833
10834            // Only privileged apps and updated privileged apps can add child packages.
10835            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10836                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10837                    throw new PackageManagerException("Only privileged apps can add child "
10838                            + "packages. Ignoring package " + pkg.packageName);
10839                }
10840                final int childCount = pkg.childPackages.size();
10841                for (int i = 0; i < childCount; i++) {
10842                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10843                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10844                            childPkg.packageName)) {
10845                        throw new PackageManagerException("Can't override child of "
10846                                + "another disabled app. Ignoring package " + pkg.packageName);
10847                    }
10848                }
10849            }
10850
10851            // If we're only installing presumed-existing packages, require that the
10852            // scanned APK is both already known and at the path previously established
10853            // for it.  Previously unknown packages we pick up normally, but if we have an
10854            // a priori expectation about this package's install presence, enforce it.
10855            // With a singular exception for new system packages. When an OTA contains
10856            // a new system package, we allow the codepath to change from a system location
10857            // to the user-installed location. If we don't allow this change, any newer,
10858            // user-installed version of the application will be ignored.
10859            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10860                if (mExpectingBetter.containsKey(pkg.packageName)) {
10861                    logCriticalInfo(Log.WARN,
10862                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10863                } else {
10864                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10865                    if (known != null) {
10866                        if (DEBUG_PACKAGE_SCANNING) {
10867                            Log.d(TAG, "Examining " + pkg.codePath
10868                                    + " and requiring known paths " + known.codePathString
10869                                    + " & " + known.resourcePathString);
10870                        }
10871                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10872                                || !pkg.applicationInfo.getResourcePath().equals(
10873                                        known.resourcePathString)) {
10874                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10875                                    "Application package " + pkg.packageName
10876                                    + " found at " + pkg.applicationInfo.getCodePath()
10877                                    + " but expected at " + known.codePathString
10878                                    + "; ignoring.");
10879                        }
10880                    }
10881                }
10882            }
10883
10884            // Verify that this new package doesn't have any content providers
10885            // that conflict with existing packages.  Only do this if the
10886            // package isn't already installed, since we don't want to break
10887            // things that are installed.
10888            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10889                final int N = pkg.providers.size();
10890                int i;
10891                for (i=0; i<N; i++) {
10892                    PackageParser.Provider p = pkg.providers.get(i);
10893                    if (p.info.authority != null) {
10894                        String names[] = p.info.authority.split(";");
10895                        for (int j = 0; j < names.length; j++) {
10896                            if (mProvidersByAuthority.containsKey(names[j])) {
10897                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10898                                final String otherPackageName =
10899                                        ((other != null && other.getComponentName() != null) ?
10900                                                other.getComponentName().getPackageName() : "?");
10901                                throw new PackageManagerException(
10902                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10903                                        "Can't install because provider name " + names[j]
10904                                                + " (in package " + pkg.applicationInfo.packageName
10905                                                + ") is already used by " + otherPackageName);
10906                            }
10907                        }
10908                    }
10909                }
10910            }
10911        }
10912    }
10913
10914    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10915            int type, String declaringPackageName, int declaringVersionCode) {
10916        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10917        if (versionedLib == null) {
10918            versionedLib = new SparseArray<>();
10919            mSharedLibraries.put(name, versionedLib);
10920            if (type == SharedLibraryInfo.TYPE_STATIC) {
10921                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10922            }
10923        } else if (versionedLib.indexOfKey(version) >= 0) {
10924            return false;
10925        }
10926        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10927                version, type, declaringPackageName, declaringVersionCode);
10928        versionedLib.put(version, libEntry);
10929        return true;
10930    }
10931
10932    private boolean removeSharedLibraryLPw(String name, int version) {
10933        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10934        if (versionedLib == null) {
10935            return false;
10936        }
10937        final int libIdx = versionedLib.indexOfKey(version);
10938        if (libIdx < 0) {
10939            return false;
10940        }
10941        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10942        versionedLib.remove(version);
10943        if (versionedLib.size() <= 0) {
10944            mSharedLibraries.remove(name);
10945            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10946                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10947                        .getPackageName());
10948            }
10949        }
10950        return true;
10951    }
10952
10953    /**
10954     * Adds a scanned package to the system. When this method is finished, the package will
10955     * be available for query, resolution, etc...
10956     */
10957    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10958            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10959        final String pkgName = pkg.packageName;
10960        if (mCustomResolverComponentName != null &&
10961                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10962            setUpCustomResolverActivity(pkg);
10963        }
10964
10965        if (pkg.packageName.equals("android")) {
10966            synchronized (mPackages) {
10967                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10968                    // Set up information for our fall-back user intent resolution activity.
10969                    mPlatformPackage = pkg;
10970                    pkg.mVersionCode = mSdkVersion;
10971                    mAndroidApplication = pkg.applicationInfo;
10972                    if (!mResolverReplaced) {
10973                        mResolveActivity.applicationInfo = mAndroidApplication;
10974                        mResolveActivity.name = ResolverActivity.class.getName();
10975                        mResolveActivity.packageName = mAndroidApplication.packageName;
10976                        mResolveActivity.processName = "system:ui";
10977                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10978                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10979                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10980                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10981                        mResolveActivity.exported = true;
10982                        mResolveActivity.enabled = true;
10983                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10984                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10985                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10986                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10987                                | ActivityInfo.CONFIG_ORIENTATION
10988                                | ActivityInfo.CONFIG_KEYBOARD
10989                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10990                        mResolveInfo.activityInfo = mResolveActivity;
10991                        mResolveInfo.priority = 0;
10992                        mResolveInfo.preferredOrder = 0;
10993                        mResolveInfo.match = 0;
10994                        mResolveComponentName = new ComponentName(
10995                                mAndroidApplication.packageName, mResolveActivity.name);
10996                    }
10997                }
10998            }
10999        }
11000
11001        ArrayList<PackageParser.Package> clientLibPkgs = null;
11002        // writer
11003        synchronized (mPackages) {
11004            boolean hasStaticSharedLibs = false;
11005
11006            // Any app can add new static shared libraries
11007            if (pkg.staticSharedLibName != null) {
11008                // Static shared libs don't allow renaming as they have synthetic package
11009                // names to allow install of multiple versions, so use name from manifest.
11010                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11011                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11012                        pkg.manifestPackageName, pkg.mVersionCode)) {
11013                    hasStaticSharedLibs = true;
11014                } else {
11015                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11016                                + pkg.staticSharedLibName + " already exists; skipping");
11017                }
11018                // Static shared libs cannot be updated once installed since they
11019                // use synthetic package name which includes the version code, so
11020                // not need to update other packages's shared lib dependencies.
11021            }
11022
11023            if (!hasStaticSharedLibs
11024                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11025                // Only system apps can add new dynamic shared libraries.
11026                if (pkg.libraryNames != null) {
11027                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11028                        String name = pkg.libraryNames.get(i);
11029                        boolean allowed = false;
11030                        if (pkg.isUpdatedSystemApp()) {
11031                            // New library entries can only be added through the
11032                            // system image.  This is important to get rid of a lot
11033                            // of nasty edge cases: for example if we allowed a non-
11034                            // system update of the app to add a library, then uninstalling
11035                            // the update would make the library go away, and assumptions
11036                            // we made such as through app install filtering would now
11037                            // have allowed apps on the device which aren't compatible
11038                            // with it.  Better to just have the restriction here, be
11039                            // conservative, and create many fewer cases that can negatively
11040                            // impact the user experience.
11041                            final PackageSetting sysPs = mSettings
11042                                    .getDisabledSystemPkgLPr(pkg.packageName);
11043                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11044                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11045                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11046                                        allowed = true;
11047                                        break;
11048                                    }
11049                                }
11050                            }
11051                        } else {
11052                            allowed = true;
11053                        }
11054                        if (allowed) {
11055                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11056                                    SharedLibraryInfo.VERSION_UNDEFINED,
11057                                    SharedLibraryInfo.TYPE_DYNAMIC,
11058                                    pkg.packageName, pkg.mVersionCode)) {
11059                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11060                                        + name + " already exists; skipping");
11061                            }
11062                        } else {
11063                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11064                                    + name + " that is not declared on system image; skipping");
11065                        }
11066                    }
11067
11068                    if ((scanFlags & SCAN_BOOTING) == 0) {
11069                        // If we are not booting, we need to update any applications
11070                        // that are clients of our shared library.  If we are booting,
11071                        // this will all be done once the scan is complete.
11072                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11073                    }
11074                }
11075            }
11076        }
11077
11078        if ((scanFlags & SCAN_BOOTING) != 0) {
11079            // No apps can run during boot scan, so they don't need to be frozen
11080        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11081            // Caller asked to not kill app, so it's probably not frozen
11082        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11083            // Caller asked us to ignore frozen check for some reason; they
11084            // probably didn't know the package name
11085        } else {
11086            // We're doing major surgery on this package, so it better be frozen
11087            // right now to keep it from launching
11088            checkPackageFrozen(pkgName);
11089        }
11090
11091        // Also need to kill any apps that are dependent on the library.
11092        if (clientLibPkgs != null) {
11093            for (int i=0; i<clientLibPkgs.size(); i++) {
11094                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11095                killApplication(clientPkg.applicationInfo.packageName,
11096                        clientPkg.applicationInfo.uid, "update lib");
11097            }
11098        }
11099
11100        // writer
11101        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11102
11103        synchronized (mPackages) {
11104            // We don't expect installation to fail beyond this point
11105
11106            // Add the new setting to mSettings
11107            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11108            // Add the new setting to mPackages
11109            mPackages.put(pkg.applicationInfo.packageName, pkg);
11110            // Make sure we don't accidentally delete its data.
11111            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11112            while (iter.hasNext()) {
11113                PackageCleanItem item = iter.next();
11114                if (pkgName.equals(item.packageName)) {
11115                    iter.remove();
11116                }
11117            }
11118
11119            // Add the package's KeySets to the global KeySetManagerService
11120            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11121            ksms.addScannedPackageLPw(pkg);
11122
11123            int N = pkg.providers.size();
11124            StringBuilder r = null;
11125            int i;
11126            for (i=0; i<N; i++) {
11127                PackageParser.Provider p = pkg.providers.get(i);
11128                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11129                        p.info.processName);
11130                mProviders.addProvider(p);
11131                p.syncable = p.info.isSyncable;
11132                if (p.info.authority != null) {
11133                    String names[] = p.info.authority.split(";");
11134                    p.info.authority = null;
11135                    for (int j = 0; j < names.length; j++) {
11136                        if (j == 1 && p.syncable) {
11137                            // We only want the first authority for a provider to possibly be
11138                            // syncable, so if we already added this provider using a different
11139                            // authority clear the syncable flag. We copy the provider before
11140                            // changing it because the mProviders object contains a reference
11141                            // to a provider that we don't want to change.
11142                            // Only do this for the second authority since the resulting provider
11143                            // object can be the same for all future authorities for this provider.
11144                            p = new PackageParser.Provider(p);
11145                            p.syncable = false;
11146                        }
11147                        if (!mProvidersByAuthority.containsKey(names[j])) {
11148                            mProvidersByAuthority.put(names[j], p);
11149                            if (p.info.authority == null) {
11150                                p.info.authority = names[j];
11151                            } else {
11152                                p.info.authority = p.info.authority + ";" + names[j];
11153                            }
11154                            if (DEBUG_PACKAGE_SCANNING) {
11155                                if (chatty)
11156                                    Log.d(TAG, "Registered content provider: " + names[j]
11157                                            + ", className = " + p.info.name + ", isSyncable = "
11158                                            + p.info.isSyncable);
11159                            }
11160                        } else {
11161                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11162                            Slog.w(TAG, "Skipping provider name " + names[j] +
11163                                    " (in package " + pkg.applicationInfo.packageName +
11164                                    "): name already used by "
11165                                    + ((other != null && other.getComponentName() != null)
11166                                            ? other.getComponentName().getPackageName() : "?"));
11167                        }
11168                    }
11169                }
11170                if (chatty) {
11171                    if (r == null) {
11172                        r = new StringBuilder(256);
11173                    } else {
11174                        r.append(' ');
11175                    }
11176                    r.append(p.info.name);
11177                }
11178            }
11179            if (r != null) {
11180                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11181            }
11182
11183            N = pkg.services.size();
11184            r = null;
11185            for (i=0; i<N; i++) {
11186                PackageParser.Service s = pkg.services.get(i);
11187                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11188                        s.info.processName);
11189                mServices.addService(s);
11190                if (chatty) {
11191                    if (r == null) {
11192                        r = new StringBuilder(256);
11193                    } else {
11194                        r.append(' ');
11195                    }
11196                    r.append(s.info.name);
11197                }
11198            }
11199            if (r != null) {
11200                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11201            }
11202
11203            N = pkg.receivers.size();
11204            r = null;
11205            for (i=0; i<N; i++) {
11206                PackageParser.Activity a = pkg.receivers.get(i);
11207                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11208                        a.info.processName);
11209                mReceivers.addActivity(a, "receiver");
11210                if (chatty) {
11211                    if (r == null) {
11212                        r = new StringBuilder(256);
11213                    } else {
11214                        r.append(' ');
11215                    }
11216                    r.append(a.info.name);
11217                }
11218            }
11219            if (r != null) {
11220                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11221            }
11222
11223            N = pkg.activities.size();
11224            r = null;
11225            for (i=0; i<N; i++) {
11226                PackageParser.Activity a = pkg.activities.get(i);
11227                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11228                        a.info.processName);
11229                mActivities.addActivity(a, "activity");
11230                if (chatty) {
11231                    if (r == null) {
11232                        r = new StringBuilder(256);
11233                    } else {
11234                        r.append(' ');
11235                    }
11236                    r.append(a.info.name);
11237                }
11238            }
11239            if (r != null) {
11240                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11241            }
11242
11243            N = pkg.permissionGroups.size();
11244            r = null;
11245            for (i=0; i<N; i++) {
11246                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11247                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11248                final String curPackageName = cur == null ? null : cur.info.packageName;
11249                // Dont allow ephemeral apps to define new permission groups.
11250                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11251                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11252                            + pg.info.packageName
11253                            + " ignored: instant apps cannot define new permission groups.");
11254                    continue;
11255                }
11256                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11257                if (cur == null || isPackageUpdate) {
11258                    mPermissionGroups.put(pg.info.name, pg);
11259                    if (chatty) {
11260                        if (r == null) {
11261                            r = new StringBuilder(256);
11262                        } else {
11263                            r.append(' ');
11264                        }
11265                        if (isPackageUpdate) {
11266                            r.append("UPD:");
11267                        }
11268                        r.append(pg.info.name);
11269                    }
11270                } else {
11271                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11272                            + pg.info.packageName + " ignored: original from "
11273                            + cur.info.packageName);
11274                    if (chatty) {
11275                        if (r == null) {
11276                            r = new StringBuilder(256);
11277                        } else {
11278                            r.append(' ');
11279                        }
11280                        r.append("DUP:");
11281                        r.append(pg.info.name);
11282                    }
11283                }
11284            }
11285            if (r != null) {
11286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11287            }
11288
11289            N = pkg.permissions.size();
11290            r = null;
11291            for (i=0; i<N; i++) {
11292                PackageParser.Permission p = pkg.permissions.get(i);
11293
11294                // Dont allow ephemeral apps to define new permissions.
11295                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11296                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11297                            + p.info.packageName
11298                            + " ignored: instant apps cannot define new permissions.");
11299                    continue;
11300                }
11301
11302                // Assume by default that we did not install this permission into the system.
11303                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11304
11305                // Now that permission groups have a special meaning, we ignore permission
11306                // groups for legacy apps to prevent unexpected behavior. In particular,
11307                // permissions for one app being granted to someone just because they happen
11308                // to be in a group defined by another app (before this had no implications).
11309                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11310                    p.group = mPermissionGroups.get(p.info.group);
11311                    // Warn for a permission in an unknown group.
11312                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11313                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11314                                + p.info.packageName + " in an unknown group " + p.info.group);
11315                    }
11316                }
11317
11318                ArrayMap<String, BasePermission> permissionMap =
11319                        p.tree ? mSettings.mPermissionTrees
11320                                : mSettings.mPermissions;
11321                BasePermission bp = permissionMap.get(p.info.name);
11322
11323                // Allow system apps to redefine non-system permissions
11324                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11325                    final boolean currentOwnerIsSystem = (bp.perm != null
11326                            && isSystemApp(bp.perm.owner));
11327                    if (isSystemApp(p.owner)) {
11328                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11329                            // It's a built-in permission and no owner, take ownership now
11330                            bp.packageSetting = pkgSetting;
11331                            bp.perm = p;
11332                            bp.uid = pkg.applicationInfo.uid;
11333                            bp.sourcePackage = p.info.packageName;
11334                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11335                        } else if (!currentOwnerIsSystem) {
11336                            String msg = "New decl " + p.owner + " of permission  "
11337                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11338                            reportSettingsProblem(Log.WARN, msg);
11339                            bp = null;
11340                        }
11341                    }
11342                }
11343
11344                if (bp == null) {
11345                    bp = new BasePermission(p.info.name, p.info.packageName,
11346                            BasePermission.TYPE_NORMAL);
11347                    permissionMap.put(p.info.name, bp);
11348                }
11349
11350                if (bp.perm == null) {
11351                    if (bp.sourcePackage == null
11352                            || bp.sourcePackage.equals(p.info.packageName)) {
11353                        BasePermission tree = findPermissionTreeLP(p.info.name);
11354                        if (tree == null
11355                                || tree.sourcePackage.equals(p.info.packageName)) {
11356                            bp.packageSetting = pkgSetting;
11357                            bp.perm = p;
11358                            bp.uid = pkg.applicationInfo.uid;
11359                            bp.sourcePackage = p.info.packageName;
11360                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11361                            if (chatty) {
11362                                if (r == null) {
11363                                    r = new StringBuilder(256);
11364                                } else {
11365                                    r.append(' ');
11366                                }
11367                                r.append(p.info.name);
11368                            }
11369                        } else {
11370                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11371                                    + p.info.packageName + " ignored: base tree "
11372                                    + tree.name + " is from package "
11373                                    + tree.sourcePackage);
11374                        }
11375                    } else {
11376                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11377                                + p.info.packageName + " ignored: original from "
11378                                + bp.sourcePackage);
11379                    }
11380                } else if (chatty) {
11381                    if (r == null) {
11382                        r = new StringBuilder(256);
11383                    } else {
11384                        r.append(' ');
11385                    }
11386                    r.append("DUP:");
11387                    r.append(p.info.name);
11388                }
11389                if (bp.perm == p) {
11390                    bp.protectionLevel = p.info.protectionLevel;
11391                }
11392            }
11393
11394            if (r != null) {
11395                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11396            }
11397
11398            N = pkg.instrumentation.size();
11399            r = null;
11400            for (i=0; i<N; i++) {
11401                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11402                a.info.packageName = pkg.applicationInfo.packageName;
11403                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11404                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11405                a.info.splitNames = pkg.splitNames;
11406                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11407                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11408                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11409                a.info.dataDir = pkg.applicationInfo.dataDir;
11410                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11411                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11412                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11413                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11414                mInstrumentation.put(a.getComponentName(), a);
11415                if (chatty) {
11416                    if (r == null) {
11417                        r = new StringBuilder(256);
11418                    } else {
11419                        r.append(' ');
11420                    }
11421                    r.append(a.info.name);
11422                }
11423            }
11424            if (r != null) {
11425                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11426            }
11427
11428            if (pkg.protectedBroadcasts != null) {
11429                N = pkg.protectedBroadcasts.size();
11430                for (i=0; i<N; i++) {
11431                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11432                }
11433            }
11434        }
11435
11436        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11437    }
11438
11439    /**
11440     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11441     * is derived purely on the basis of the contents of {@code scanFile} and
11442     * {@code cpuAbiOverride}.
11443     *
11444     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11445     */
11446    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11447                                 String cpuAbiOverride, boolean extractLibs,
11448                                 File appLib32InstallDir)
11449            throws PackageManagerException {
11450        // Give ourselves some initial paths; we'll come back for another
11451        // pass once we've determined ABI below.
11452        setNativeLibraryPaths(pkg, appLib32InstallDir);
11453
11454        // We would never need to extract libs for forward-locked and external packages,
11455        // since the container service will do it for us. We shouldn't attempt to
11456        // extract libs from system app when it was not updated.
11457        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11458                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11459            extractLibs = false;
11460        }
11461
11462        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11463        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11464
11465        NativeLibraryHelper.Handle handle = null;
11466        try {
11467            handle = NativeLibraryHelper.Handle.create(pkg);
11468            // TODO(multiArch): This can be null for apps that didn't go through the
11469            // usual installation process. We can calculate it again, like we
11470            // do during install time.
11471            //
11472            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11473            // unnecessary.
11474            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11475
11476            // Null out the abis so that they can be recalculated.
11477            pkg.applicationInfo.primaryCpuAbi = null;
11478            pkg.applicationInfo.secondaryCpuAbi = null;
11479            if (isMultiArch(pkg.applicationInfo)) {
11480                // Warn if we've set an abiOverride for multi-lib packages..
11481                // By definition, we need to copy both 32 and 64 bit libraries for
11482                // such packages.
11483                if (pkg.cpuAbiOverride != null
11484                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11485                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11486                }
11487
11488                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11489                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11490                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11491                    if (extractLibs) {
11492                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11493                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11494                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11495                                useIsaSpecificSubdirs);
11496                    } else {
11497                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11498                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11499                    }
11500                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11501                }
11502
11503                maybeThrowExceptionForMultiArchCopy(
11504                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11505
11506                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11507                    if (extractLibs) {
11508                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11509                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11510                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11511                                useIsaSpecificSubdirs);
11512                    } else {
11513                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11514                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11515                    }
11516                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11517                }
11518
11519                maybeThrowExceptionForMultiArchCopy(
11520                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11521
11522                if (abi64 >= 0) {
11523                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11524                }
11525
11526                if (abi32 >= 0) {
11527                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11528                    if (abi64 >= 0) {
11529                        if (pkg.use32bitAbi) {
11530                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11531                            pkg.applicationInfo.primaryCpuAbi = abi;
11532                        } else {
11533                            pkg.applicationInfo.secondaryCpuAbi = abi;
11534                        }
11535                    } else {
11536                        pkg.applicationInfo.primaryCpuAbi = abi;
11537                    }
11538                }
11539
11540            } else {
11541                String[] abiList = (cpuAbiOverride != null) ?
11542                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11543
11544                // Enable gross and lame hacks for apps that are built with old
11545                // SDK tools. We must scan their APKs for renderscript bitcode and
11546                // not launch them if it's present. Don't bother checking on devices
11547                // that don't have 64 bit support.
11548                boolean needsRenderScriptOverride = false;
11549                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11550                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11551                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11552                    needsRenderScriptOverride = true;
11553                }
11554
11555                final int copyRet;
11556                if (extractLibs) {
11557                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11558                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11559                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11560                } else {
11561                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11562                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11563                }
11564                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11565
11566                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11567                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11568                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11569                }
11570
11571                if (copyRet >= 0) {
11572                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11573                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11574                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11575                } else if (needsRenderScriptOverride) {
11576                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11577                }
11578            }
11579        } catch (IOException ioe) {
11580            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11581        } finally {
11582            IoUtils.closeQuietly(handle);
11583        }
11584
11585        // Now that we've calculated the ABIs and determined if it's an internal app,
11586        // we will go ahead and populate the nativeLibraryPath.
11587        setNativeLibraryPaths(pkg, appLib32InstallDir);
11588    }
11589
11590    /**
11591     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11592     * i.e, so that all packages can be run inside a single process if required.
11593     *
11594     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11595     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11596     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11597     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11598     * updating a package that belongs to a shared user.
11599     *
11600     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11601     * adds unnecessary complexity.
11602     */
11603    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11604            PackageParser.Package scannedPackage) {
11605        String requiredInstructionSet = null;
11606        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11607            requiredInstructionSet = VMRuntime.getInstructionSet(
11608                     scannedPackage.applicationInfo.primaryCpuAbi);
11609        }
11610
11611        PackageSetting requirer = null;
11612        for (PackageSetting ps : packagesForUser) {
11613            // If packagesForUser contains scannedPackage, we skip it. This will happen
11614            // when scannedPackage is an update of an existing package. Without this check,
11615            // we will never be able to change the ABI of any package belonging to a shared
11616            // user, even if it's compatible with other packages.
11617            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11618                if (ps.primaryCpuAbiString == null) {
11619                    continue;
11620                }
11621
11622                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11623                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11624                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11625                    // this but there's not much we can do.
11626                    String errorMessage = "Instruction set mismatch, "
11627                            + ((requirer == null) ? "[caller]" : requirer)
11628                            + " requires " + requiredInstructionSet + " whereas " + ps
11629                            + " requires " + instructionSet;
11630                    Slog.w(TAG, errorMessage);
11631                }
11632
11633                if (requiredInstructionSet == null) {
11634                    requiredInstructionSet = instructionSet;
11635                    requirer = ps;
11636                }
11637            }
11638        }
11639
11640        if (requiredInstructionSet != null) {
11641            String adjustedAbi;
11642            if (requirer != null) {
11643                // requirer != null implies that either scannedPackage was null or that scannedPackage
11644                // did not require an ABI, in which case we have to adjust scannedPackage to match
11645                // the ABI of the set (which is the same as requirer's ABI)
11646                adjustedAbi = requirer.primaryCpuAbiString;
11647                if (scannedPackage != null) {
11648                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11649                }
11650            } else {
11651                // requirer == null implies that we're updating all ABIs in the set to
11652                // match scannedPackage.
11653                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11654            }
11655
11656            for (PackageSetting ps : packagesForUser) {
11657                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11658                    if (ps.primaryCpuAbiString != null) {
11659                        continue;
11660                    }
11661
11662                    ps.primaryCpuAbiString = adjustedAbi;
11663                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11664                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11665                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11666                        if (DEBUG_ABI_SELECTION) {
11667                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11668                                    + " (requirer="
11669                                    + (requirer != null ? requirer.pkg : "null")
11670                                    + ", scannedPackage="
11671                                    + (scannedPackage != null ? scannedPackage : "null")
11672                                    + ")");
11673                        }
11674                        try {
11675                            mInstaller.rmdex(ps.codePathString,
11676                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11677                        } catch (InstallerException ignored) {
11678                        }
11679                    }
11680                }
11681            }
11682        }
11683    }
11684
11685    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11686        synchronized (mPackages) {
11687            mResolverReplaced = true;
11688            // Set up information for custom user intent resolution activity.
11689            mResolveActivity.applicationInfo = pkg.applicationInfo;
11690            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11691            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11692            mResolveActivity.processName = pkg.applicationInfo.packageName;
11693            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11694            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11695                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11696            mResolveActivity.theme = 0;
11697            mResolveActivity.exported = true;
11698            mResolveActivity.enabled = true;
11699            mResolveInfo.activityInfo = mResolveActivity;
11700            mResolveInfo.priority = 0;
11701            mResolveInfo.preferredOrder = 0;
11702            mResolveInfo.match = 0;
11703            mResolveComponentName = mCustomResolverComponentName;
11704            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11705                    mResolveComponentName);
11706        }
11707    }
11708
11709    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11710        if (installerActivity == null) {
11711            if (DEBUG_EPHEMERAL) {
11712                Slog.d(TAG, "Clear ephemeral installer activity");
11713            }
11714            mInstantAppInstallerActivity = null;
11715            return;
11716        }
11717
11718        if (DEBUG_EPHEMERAL) {
11719            Slog.d(TAG, "Set ephemeral installer activity: "
11720                    + installerActivity.getComponentName());
11721        }
11722        // Set up information for ephemeral installer activity
11723        mInstantAppInstallerActivity = installerActivity;
11724        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11725                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11726        mInstantAppInstallerActivity.exported = true;
11727        mInstantAppInstallerActivity.enabled = true;
11728        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11729        mInstantAppInstallerInfo.priority = 0;
11730        mInstantAppInstallerInfo.preferredOrder = 1;
11731        mInstantAppInstallerInfo.isDefault = true;
11732        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11733                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11734    }
11735
11736    private static String calculateBundledApkRoot(final String codePathString) {
11737        final File codePath = new File(codePathString);
11738        final File codeRoot;
11739        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11740            codeRoot = Environment.getRootDirectory();
11741        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11742            codeRoot = Environment.getOemDirectory();
11743        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11744            codeRoot = Environment.getVendorDirectory();
11745        } else {
11746            // Unrecognized code path; take its top real segment as the apk root:
11747            // e.g. /something/app/blah.apk => /something
11748            try {
11749                File f = codePath.getCanonicalFile();
11750                File parent = f.getParentFile();    // non-null because codePath is a file
11751                File tmp;
11752                while ((tmp = parent.getParentFile()) != null) {
11753                    f = parent;
11754                    parent = tmp;
11755                }
11756                codeRoot = f;
11757                Slog.w(TAG, "Unrecognized code path "
11758                        + codePath + " - using " + codeRoot);
11759            } catch (IOException e) {
11760                // Can't canonicalize the code path -- shenanigans?
11761                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11762                return Environment.getRootDirectory().getPath();
11763            }
11764        }
11765        return codeRoot.getPath();
11766    }
11767
11768    /**
11769     * Derive and set the location of native libraries for the given package,
11770     * which varies depending on where and how the package was installed.
11771     */
11772    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11773        final ApplicationInfo info = pkg.applicationInfo;
11774        final String codePath = pkg.codePath;
11775        final File codeFile = new File(codePath);
11776        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11777        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11778
11779        info.nativeLibraryRootDir = null;
11780        info.nativeLibraryRootRequiresIsa = false;
11781        info.nativeLibraryDir = null;
11782        info.secondaryNativeLibraryDir = null;
11783
11784        if (isApkFile(codeFile)) {
11785            // Monolithic install
11786            if (bundledApp) {
11787                // If "/system/lib64/apkname" exists, assume that is the per-package
11788                // native library directory to use; otherwise use "/system/lib/apkname".
11789                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11790                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11791                        getPrimaryInstructionSet(info));
11792
11793                // This is a bundled system app so choose the path based on the ABI.
11794                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11795                // is just the default path.
11796                final String apkName = deriveCodePathName(codePath);
11797                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11798                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11799                        apkName).getAbsolutePath();
11800
11801                if (info.secondaryCpuAbi != null) {
11802                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11803                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11804                            secondaryLibDir, apkName).getAbsolutePath();
11805                }
11806            } else if (asecApp) {
11807                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11808                        .getAbsolutePath();
11809            } else {
11810                final String apkName = deriveCodePathName(codePath);
11811                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11812                        .getAbsolutePath();
11813            }
11814
11815            info.nativeLibraryRootRequiresIsa = false;
11816            info.nativeLibraryDir = info.nativeLibraryRootDir;
11817        } else {
11818            // Cluster install
11819            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11820            info.nativeLibraryRootRequiresIsa = true;
11821
11822            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11823                    getPrimaryInstructionSet(info)).getAbsolutePath();
11824
11825            if (info.secondaryCpuAbi != null) {
11826                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11827                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11828            }
11829        }
11830    }
11831
11832    /**
11833     * Calculate the abis and roots for a bundled app. These can uniquely
11834     * be determined from the contents of the system partition, i.e whether
11835     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11836     * of this information, and instead assume that the system was built
11837     * sensibly.
11838     */
11839    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11840                                           PackageSetting pkgSetting) {
11841        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11842
11843        // If "/system/lib64/apkname" exists, assume that is the per-package
11844        // native library directory to use; otherwise use "/system/lib/apkname".
11845        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11846        setBundledAppAbi(pkg, apkRoot, apkName);
11847        // pkgSetting might be null during rescan following uninstall of updates
11848        // to a bundled app, so accommodate that possibility.  The settings in
11849        // that case will be established later from the parsed package.
11850        //
11851        // If the settings aren't null, sync them up with what we've just derived.
11852        // note that apkRoot isn't stored in the package settings.
11853        if (pkgSetting != null) {
11854            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11855            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11856        }
11857    }
11858
11859    /**
11860     * Deduces the ABI of a bundled app and sets the relevant fields on the
11861     * parsed pkg object.
11862     *
11863     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11864     *        under which system libraries are installed.
11865     * @param apkName the name of the installed package.
11866     */
11867    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11868        final File codeFile = new File(pkg.codePath);
11869
11870        final boolean has64BitLibs;
11871        final boolean has32BitLibs;
11872        if (isApkFile(codeFile)) {
11873            // Monolithic install
11874            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11875            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11876        } else {
11877            // Cluster install
11878            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11879            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11880                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11881                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11882                has64BitLibs = (new File(rootDir, isa)).exists();
11883            } else {
11884                has64BitLibs = false;
11885            }
11886            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11887                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11888                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11889                has32BitLibs = (new File(rootDir, isa)).exists();
11890            } else {
11891                has32BitLibs = false;
11892            }
11893        }
11894
11895        if (has64BitLibs && !has32BitLibs) {
11896            // The package has 64 bit libs, but not 32 bit libs. Its primary
11897            // ABI should be 64 bit. We can safely assume here that the bundled
11898            // native libraries correspond to the most preferred ABI in the list.
11899
11900            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11901            pkg.applicationInfo.secondaryCpuAbi = null;
11902        } else if (has32BitLibs && !has64BitLibs) {
11903            // The package has 32 bit libs but not 64 bit libs. Its primary
11904            // ABI should be 32 bit.
11905
11906            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11907            pkg.applicationInfo.secondaryCpuAbi = null;
11908        } else if (has32BitLibs && has64BitLibs) {
11909            // The application has both 64 and 32 bit bundled libraries. We check
11910            // here that the app declares multiArch support, and warn if it doesn't.
11911            //
11912            // We will be lenient here and record both ABIs. The primary will be the
11913            // ABI that's higher on the list, i.e, a device that's configured to prefer
11914            // 64 bit apps will see a 64 bit primary ABI,
11915
11916            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11917                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11918            }
11919
11920            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11921                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11922                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11923            } else {
11924                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11925                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11926            }
11927        } else {
11928            pkg.applicationInfo.primaryCpuAbi = null;
11929            pkg.applicationInfo.secondaryCpuAbi = null;
11930        }
11931    }
11932
11933    private void killApplication(String pkgName, int appId, String reason) {
11934        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11935    }
11936
11937    private void killApplication(String pkgName, int appId, int userId, String reason) {
11938        // Request the ActivityManager to kill the process(only for existing packages)
11939        // so that we do not end up in a confused state while the user is still using the older
11940        // version of the application while the new one gets installed.
11941        final long token = Binder.clearCallingIdentity();
11942        try {
11943            IActivityManager am = ActivityManager.getService();
11944            if (am != null) {
11945                try {
11946                    am.killApplication(pkgName, appId, userId, reason);
11947                } catch (RemoteException e) {
11948                }
11949            }
11950        } finally {
11951            Binder.restoreCallingIdentity(token);
11952        }
11953    }
11954
11955    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11956        // Remove the parent package setting
11957        PackageSetting ps = (PackageSetting) pkg.mExtras;
11958        if (ps != null) {
11959            removePackageLI(ps, chatty);
11960        }
11961        // Remove the child package setting
11962        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11963        for (int i = 0; i < childCount; i++) {
11964            PackageParser.Package childPkg = pkg.childPackages.get(i);
11965            ps = (PackageSetting) childPkg.mExtras;
11966            if (ps != null) {
11967                removePackageLI(ps, chatty);
11968            }
11969        }
11970    }
11971
11972    void removePackageLI(PackageSetting ps, boolean chatty) {
11973        if (DEBUG_INSTALL) {
11974            if (chatty)
11975                Log.d(TAG, "Removing package " + ps.name);
11976        }
11977
11978        // writer
11979        synchronized (mPackages) {
11980            mPackages.remove(ps.name);
11981            final PackageParser.Package pkg = ps.pkg;
11982            if (pkg != null) {
11983                cleanPackageDataStructuresLILPw(pkg, chatty);
11984            }
11985        }
11986    }
11987
11988    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11989        if (DEBUG_INSTALL) {
11990            if (chatty)
11991                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11992        }
11993
11994        // writer
11995        synchronized (mPackages) {
11996            // Remove the parent package
11997            mPackages.remove(pkg.applicationInfo.packageName);
11998            cleanPackageDataStructuresLILPw(pkg, chatty);
11999
12000            // Remove the child packages
12001            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12002            for (int i = 0; i < childCount; i++) {
12003                PackageParser.Package childPkg = pkg.childPackages.get(i);
12004                mPackages.remove(childPkg.applicationInfo.packageName);
12005                cleanPackageDataStructuresLILPw(childPkg, chatty);
12006            }
12007        }
12008    }
12009
12010    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12011        int N = pkg.providers.size();
12012        StringBuilder r = null;
12013        int i;
12014        for (i=0; i<N; i++) {
12015            PackageParser.Provider p = pkg.providers.get(i);
12016            mProviders.removeProvider(p);
12017            if (p.info.authority == null) {
12018
12019                /* There was another ContentProvider with this authority when
12020                 * this app was installed so this authority is null,
12021                 * Ignore it as we don't have to unregister the provider.
12022                 */
12023                continue;
12024            }
12025            String names[] = p.info.authority.split(";");
12026            for (int j = 0; j < names.length; j++) {
12027                if (mProvidersByAuthority.get(names[j]) == p) {
12028                    mProvidersByAuthority.remove(names[j]);
12029                    if (DEBUG_REMOVE) {
12030                        if (chatty)
12031                            Log.d(TAG, "Unregistered content provider: " + names[j]
12032                                    + ", className = " + p.info.name + ", isSyncable = "
12033                                    + p.info.isSyncable);
12034                    }
12035                }
12036            }
12037            if (DEBUG_REMOVE && chatty) {
12038                if (r == null) {
12039                    r = new StringBuilder(256);
12040                } else {
12041                    r.append(' ');
12042                }
12043                r.append(p.info.name);
12044            }
12045        }
12046        if (r != null) {
12047            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12048        }
12049
12050        N = pkg.services.size();
12051        r = null;
12052        for (i=0; i<N; i++) {
12053            PackageParser.Service s = pkg.services.get(i);
12054            mServices.removeService(s);
12055            if (chatty) {
12056                if (r == null) {
12057                    r = new StringBuilder(256);
12058                } else {
12059                    r.append(' ');
12060                }
12061                r.append(s.info.name);
12062            }
12063        }
12064        if (r != null) {
12065            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12066        }
12067
12068        N = pkg.receivers.size();
12069        r = null;
12070        for (i=0; i<N; i++) {
12071            PackageParser.Activity a = pkg.receivers.get(i);
12072            mReceivers.removeActivity(a, "receiver");
12073            if (DEBUG_REMOVE && chatty) {
12074                if (r == null) {
12075                    r = new StringBuilder(256);
12076                } else {
12077                    r.append(' ');
12078                }
12079                r.append(a.info.name);
12080            }
12081        }
12082        if (r != null) {
12083            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12084        }
12085
12086        N = pkg.activities.size();
12087        r = null;
12088        for (i=0; i<N; i++) {
12089            PackageParser.Activity a = pkg.activities.get(i);
12090            mActivities.removeActivity(a, "activity");
12091            if (DEBUG_REMOVE && chatty) {
12092                if (r == null) {
12093                    r = new StringBuilder(256);
12094                } else {
12095                    r.append(' ');
12096                }
12097                r.append(a.info.name);
12098            }
12099        }
12100        if (r != null) {
12101            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12102        }
12103
12104        N = pkg.permissions.size();
12105        r = null;
12106        for (i=0; i<N; i++) {
12107            PackageParser.Permission p = pkg.permissions.get(i);
12108            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12109            if (bp == null) {
12110                bp = mSettings.mPermissionTrees.get(p.info.name);
12111            }
12112            if (bp != null && bp.perm == p) {
12113                bp.perm = null;
12114                if (DEBUG_REMOVE && chatty) {
12115                    if (r == null) {
12116                        r = new StringBuilder(256);
12117                    } else {
12118                        r.append(' ');
12119                    }
12120                    r.append(p.info.name);
12121                }
12122            }
12123            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12124                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12125                if (appOpPkgs != null) {
12126                    appOpPkgs.remove(pkg.packageName);
12127                }
12128            }
12129        }
12130        if (r != null) {
12131            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12132        }
12133
12134        N = pkg.requestedPermissions.size();
12135        r = null;
12136        for (i=0; i<N; i++) {
12137            String perm = pkg.requestedPermissions.get(i);
12138            BasePermission bp = mSettings.mPermissions.get(perm);
12139            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12140                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12141                if (appOpPkgs != null) {
12142                    appOpPkgs.remove(pkg.packageName);
12143                    if (appOpPkgs.isEmpty()) {
12144                        mAppOpPermissionPackages.remove(perm);
12145                    }
12146                }
12147            }
12148        }
12149        if (r != null) {
12150            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12151        }
12152
12153        N = pkg.instrumentation.size();
12154        r = null;
12155        for (i=0; i<N; i++) {
12156            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12157            mInstrumentation.remove(a.getComponentName());
12158            if (DEBUG_REMOVE && chatty) {
12159                if (r == null) {
12160                    r = new StringBuilder(256);
12161                } else {
12162                    r.append(' ');
12163                }
12164                r.append(a.info.name);
12165            }
12166        }
12167        if (r != null) {
12168            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12169        }
12170
12171        r = null;
12172        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12173            // Only system apps can hold shared libraries.
12174            if (pkg.libraryNames != null) {
12175                for (i = 0; i < pkg.libraryNames.size(); i++) {
12176                    String name = pkg.libraryNames.get(i);
12177                    if (removeSharedLibraryLPw(name, 0)) {
12178                        if (DEBUG_REMOVE && chatty) {
12179                            if (r == null) {
12180                                r = new StringBuilder(256);
12181                            } else {
12182                                r.append(' ');
12183                            }
12184                            r.append(name);
12185                        }
12186                    }
12187                }
12188            }
12189        }
12190
12191        r = null;
12192
12193        // Any package can hold static shared libraries.
12194        if (pkg.staticSharedLibName != null) {
12195            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12196                if (DEBUG_REMOVE && chatty) {
12197                    if (r == null) {
12198                        r = new StringBuilder(256);
12199                    } else {
12200                        r.append(' ');
12201                    }
12202                    r.append(pkg.staticSharedLibName);
12203                }
12204            }
12205        }
12206
12207        if (r != null) {
12208            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12209        }
12210    }
12211
12212    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12213        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12214            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12215                return true;
12216            }
12217        }
12218        return false;
12219    }
12220
12221    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12222    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12223    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12224
12225    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12226        // Update the parent permissions
12227        updatePermissionsLPw(pkg.packageName, pkg, flags);
12228        // Update the child permissions
12229        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12230        for (int i = 0; i < childCount; i++) {
12231            PackageParser.Package childPkg = pkg.childPackages.get(i);
12232            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12233        }
12234    }
12235
12236    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12237            int flags) {
12238        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12239        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12240    }
12241
12242    private void updatePermissionsLPw(String changingPkg,
12243            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12244        // Make sure there are no dangling permission trees.
12245        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12246        while (it.hasNext()) {
12247            final BasePermission bp = it.next();
12248            if (bp.packageSetting == null) {
12249                // We may not yet have parsed the package, so just see if
12250                // we still know about its settings.
12251                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12252            }
12253            if (bp.packageSetting == null) {
12254                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12255                        + " from package " + bp.sourcePackage);
12256                it.remove();
12257            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12258                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12259                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12260                            + " from package " + bp.sourcePackage);
12261                    flags |= UPDATE_PERMISSIONS_ALL;
12262                    it.remove();
12263                }
12264            }
12265        }
12266
12267        // Make sure all dynamic permissions have been assigned to a package,
12268        // and make sure there are no dangling permissions.
12269        it = mSettings.mPermissions.values().iterator();
12270        while (it.hasNext()) {
12271            final BasePermission bp = it.next();
12272            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12273                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12274                        + bp.name + " pkg=" + bp.sourcePackage
12275                        + " info=" + bp.pendingInfo);
12276                if (bp.packageSetting == null && bp.pendingInfo != null) {
12277                    final BasePermission tree = findPermissionTreeLP(bp.name);
12278                    if (tree != null && tree.perm != null) {
12279                        bp.packageSetting = tree.packageSetting;
12280                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12281                                new PermissionInfo(bp.pendingInfo));
12282                        bp.perm.info.packageName = tree.perm.info.packageName;
12283                        bp.perm.info.name = bp.name;
12284                        bp.uid = tree.uid;
12285                    }
12286                }
12287            }
12288            if (bp.packageSetting == null) {
12289                // We may not yet have parsed the package, so just see if
12290                // we still know about its settings.
12291                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12292            }
12293            if (bp.packageSetting == null) {
12294                Slog.w(TAG, "Removing dangling permission: " + bp.name
12295                        + " from package " + bp.sourcePackage);
12296                it.remove();
12297            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12298                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12299                    Slog.i(TAG, "Removing old permission: " + bp.name
12300                            + " from package " + bp.sourcePackage);
12301                    flags |= UPDATE_PERMISSIONS_ALL;
12302                    it.remove();
12303                }
12304            }
12305        }
12306
12307        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12308        // Now update the permissions for all packages, in particular
12309        // replace the granted permissions of the system packages.
12310        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12311            for (PackageParser.Package pkg : mPackages.values()) {
12312                if (pkg != pkgInfo) {
12313                    // Only replace for packages on requested volume
12314                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12315                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12316                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12317                    grantPermissionsLPw(pkg, replace, changingPkg);
12318                }
12319            }
12320        }
12321
12322        if (pkgInfo != null) {
12323            // Only replace for packages on requested volume
12324            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12325            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12326                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12327            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12328        }
12329        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12330    }
12331
12332    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12333            String packageOfInterest) {
12334        // IMPORTANT: There are two types of permissions: install and runtime.
12335        // Install time permissions are granted when the app is installed to
12336        // all device users and users added in the future. Runtime permissions
12337        // are granted at runtime explicitly to specific users. Normal and signature
12338        // protected permissions are install time permissions. Dangerous permissions
12339        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12340        // otherwise they are runtime permissions. This function does not manage
12341        // runtime permissions except for the case an app targeting Lollipop MR1
12342        // being upgraded to target a newer SDK, in which case dangerous permissions
12343        // are transformed from install time to runtime ones.
12344
12345        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12346        if (ps == null) {
12347            return;
12348        }
12349
12350        PermissionsState permissionsState = ps.getPermissionsState();
12351        PermissionsState origPermissions = permissionsState;
12352
12353        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12354
12355        boolean runtimePermissionsRevoked = false;
12356        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12357
12358        boolean changedInstallPermission = false;
12359
12360        if (replace) {
12361            ps.installPermissionsFixed = false;
12362            if (!ps.isSharedUser()) {
12363                origPermissions = new PermissionsState(permissionsState);
12364                permissionsState.reset();
12365            } else {
12366                // We need to know only about runtime permission changes since the
12367                // calling code always writes the install permissions state but
12368                // the runtime ones are written only if changed. The only cases of
12369                // changed runtime permissions here are promotion of an install to
12370                // runtime and revocation of a runtime from a shared user.
12371                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12372                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12373                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12374                    runtimePermissionsRevoked = true;
12375                }
12376            }
12377        }
12378
12379        permissionsState.setGlobalGids(mGlobalGids);
12380
12381        final int N = pkg.requestedPermissions.size();
12382        for (int i=0; i<N; i++) {
12383            final String name = pkg.requestedPermissions.get(i);
12384            final BasePermission bp = mSettings.mPermissions.get(name);
12385            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12386                    >= Build.VERSION_CODES.M;
12387
12388            if (DEBUG_INSTALL) {
12389                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12390            }
12391
12392            if (bp == null || bp.packageSetting == null) {
12393                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12394                    if (DEBUG_PERMISSIONS) {
12395                        Slog.i(TAG, "Unknown permission " + name
12396                                + " in package " + pkg.packageName);
12397                    }
12398                }
12399                continue;
12400            }
12401
12402
12403            // Limit ephemeral apps to ephemeral allowed permissions.
12404            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12405                if (DEBUG_PERMISSIONS) {
12406                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12407                            + pkg.packageName);
12408                }
12409                continue;
12410            }
12411
12412            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12413                if (DEBUG_PERMISSIONS) {
12414                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12415                            + pkg.packageName);
12416                }
12417                continue;
12418            }
12419
12420            final String perm = bp.name;
12421            boolean allowedSig = false;
12422            int grant = GRANT_DENIED;
12423
12424            // Keep track of app op permissions.
12425            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12426                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12427                if (pkgs == null) {
12428                    pkgs = new ArraySet<>();
12429                    mAppOpPermissionPackages.put(bp.name, pkgs);
12430                }
12431                pkgs.add(pkg.packageName);
12432            }
12433
12434            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12435            switch (level) {
12436                case PermissionInfo.PROTECTION_NORMAL: {
12437                    // For all apps normal permissions are install time ones.
12438                    grant = GRANT_INSTALL;
12439                } break;
12440
12441                case PermissionInfo.PROTECTION_DANGEROUS: {
12442                    // If a permission review is required for legacy apps we represent
12443                    // their permissions as always granted runtime ones since we need
12444                    // to keep the review required permission flag per user while an
12445                    // install permission's state is shared across all users.
12446                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12447                        // For legacy apps dangerous permissions are install time ones.
12448                        grant = GRANT_INSTALL;
12449                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12450                        // For legacy apps that became modern, install becomes runtime.
12451                        grant = GRANT_UPGRADE;
12452                    } else if (mPromoteSystemApps
12453                            && isSystemApp(ps)
12454                            && mExistingSystemPackages.contains(ps.name)) {
12455                        // For legacy system apps, install becomes runtime.
12456                        // We cannot check hasInstallPermission() for system apps since those
12457                        // permissions were granted implicitly and not persisted pre-M.
12458                        grant = GRANT_UPGRADE;
12459                    } else {
12460                        // For modern apps keep runtime permissions unchanged.
12461                        grant = GRANT_RUNTIME;
12462                    }
12463                } break;
12464
12465                case PermissionInfo.PROTECTION_SIGNATURE: {
12466                    // For all apps signature permissions are install time ones.
12467                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12468                    if (allowedSig) {
12469                        grant = GRANT_INSTALL;
12470                    }
12471                } break;
12472            }
12473
12474            if (DEBUG_PERMISSIONS) {
12475                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12476            }
12477
12478            if (grant != GRANT_DENIED) {
12479                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12480                    // If this is an existing, non-system package, then
12481                    // we can't add any new permissions to it.
12482                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12483                        // Except...  if this is a permission that was added
12484                        // to the platform (note: need to only do this when
12485                        // updating the platform).
12486                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12487                            grant = GRANT_DENIED;
12488                        }
12489                    }
12490                }
12491
12492                switch (grant) {
12493                    case GRANT_INSTALL: {
12494                        // Revoke this as runtime permission to handle the case of
12495                        // a runtime permission being downgraded to an install one.
12496                        // Also in permission review mode we keep dangerous permissions
12497                        // for legacy apps
12498                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12499                            if (origPermissions.getRuntimePermissionState(
12500                                    bp.name, userId) != null) {
12501                                // Revoke the runtime permission and clear the flags.
12502                                origPermissions.revokeRuntimePermission(bp, userId);
12503                                origPermissions.updatePermissionFlags(bp, userId,
12504                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12505                                // If we revoked a permission permission, we have to write.
12506                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12507                                        changedRuntimePermissionUserIds, userId);
12508                            }
12509                        }
12510                        // Grant an install permission.
12511                        if (permissionsState.grantInstallPermission(bp) !=
12512                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12513                            changedInstallPermission = true;
12514                        }
12515                    } break;
12516
12517                    case GRANT_RUNTIME: {
12518                        // Grant previously granted runtime permissions.
12519                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12520                            PermissionState permissionState = origPermissions
12521                                    .getRuntimePermissionState(bp.name, userId);
12522                            int flags = permissionState != null
12523                                    ? permissionState.getFlags() : 0;
12524                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12525                                // Don't propagate the permission in a permission review mode if
12526                                // the former was revoked, i.e. marked to not propagate on upgrade.
12527                                // Note that in a permission review mode install permissions are
12528                                // represented as constantly granted runtime ones since we need to
12529                                // keep a per user state associated with the permission. Also the
12530                                // revoke on upgrade flag is no longer applicable and is reset.
12531                                final boolean revokeOnUpgrade = (flags & PackageManager
12532                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12533                                if (revokeOnUpgrade) {
12534                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12535                                    // Since we changed the flags, we have to write.
12536                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12537                                            changedRuntimePermissionUserIds, userId);
12538                                }
12539                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12540                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12541                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12542                                        // If we cannot put the permission as it was,
12543                                        // we have to write.
12544                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12545                                                changedRuntimePermissionUserIds, userId);
12546                                    }
12547                                }
12548
12549                                // If the app supports runtime permissions no need for a review.
12550                                if (mPermissionReviewRequired
12551                                        && appSupportsRuntimePermissions
12552                                        && (flags & PackageManager
12553                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12554                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12555                                    // Since we changed the flags, we have to write.
12556                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12557                                            changedRuntimePermissionUserIds, userId);
12558                                }
12559                            } else if (mPermissionReviewRequired
12560                                    && !appSupportsRuntimePermissions) {
12561                                // For legacy apps that need a permission review, every new
12562                                // runtime permission is granted but it is pending a review.
12563                                // We also need to review only platform defined runtime
12564                                // permissions as these are the only ones the platform knows
12565                                // how to disable the API to simulate revocation as legacy
12566                                // apps don't expect to run with revoked permissions.
12567                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12568                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12569                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12570                                        // We changed the flags, hence have to write.
12571                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12572                                                changedRuntimePermissionUserIds, userId);
12573                                    }
12574                                }
12575                                if (permissionsState.grantRuntimePermission(bp, userId)
12576                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12577                                    // We changed the permission, hence have to write.
12578                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12579                                            changedRuntimePermissionUserIds, userId);
12580                                }
12581                            }
12582                            // Propagate the permission flags.
12583                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12584                        }
12585                    } break;
12586
12587                    case GRANT_UPGRADE: {
12588                        // Grant runtime permissions for a previously held install permission.
12589                        PermissionState permissionState = origPermissions
12590                                .getInstallPermissionState(bp.name);
12591                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12592
12593                        if (origPermissions.revokeInstallPermission(bp)
12594                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12595                            // We will be transferring the permission flags, so clear them.
12596                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12597                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12598                            changedInstallPermission = true;
12599                        }
12600
12601                        // If the permission is not to be promoted to runtime we ignore it and
12602                        // also its other flags as they are not applicable to install permissions.
12603                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12604                            for (int userId : currentUserIds) {
12605                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12606                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12607                                    // Transfer the permission flags.
12608                                    permissionsState.updatePermissionFlags(bp, userId,
12609                                            flags, flags);
12610                                    // If we granted the permission, we have to write.
12611                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12612                                            changedRuntimePermissionUserIds, userId);
12613                                }
12614                            }
12615                        }
12616                    } break;
12617
12618                    default: {
12619                        if (packageOfInterest == null
12620                                || packageOfInterest.equals(pkg.packageName)) {
12621                            if (DEBUG_PERMISSIONS) {
12622                                Slog.i(TAG, "Not granting permission " + perm
12623                                        + " to package " + pkg.packageName
12624                                        + " because it was previously installed without");
12625                            }
12626                        }
12627                    } break;
12628                }
12629            } else {
12630                if (permissionsState.revokeInstallPermission(bp) !=
12631                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12632                    // Also drop the permission flags.
12633                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12634                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12635                    changedInstallPermission = true;
12636                    Slog.i(TAG, "Un-granting permission " + perm
12637                            + " from package " + pkg.packageName
12638                            + " (protectionLevel=" + bp.protectionLevel
12639                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12640                            + ")");
12641                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12642                    // Don't print warning for app op permissions, since it is fine for them
12643                    // not to be granted, there is a UI for the user to decide.
12644                    if (DEBUG_PERMISSIONS
12645                            && (packageOfInterest == null
12646                                    || packageOfInterest.equals(pkg.packageName))) {
12647                        Slog.i(TAG, "Not granting permission " + perm
12648                                + " to package " + pkg.packageName
12649                                + " (protectionLevel=" + bp.protectionLevel
12650                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12651                                + ")");
12652                    }
12653                }
12654            }
12655        }
12656
12657        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12658                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12659            // This is the first that we have heard about this package, so the
12660            // permissions we have now selected are fixed until explicitly
12661            // changed.
12662            ps.installPermissionsFixed = true;
12663        }
12664
12665        // Persist the runtime permissions state for users with changes. If permissions
12666        // were revoked because no app in the shared user declares them we have to
12667        // write synchronously to avoid losing runtime permissions state.
12668        for (int userId : changedRuntimePermissionUserIds) {
12669            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12670        }
12671    }
12672
12673    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12674        boolean allowed = false;
12675        final int NP = PackageParser.NEW_PERMISSIONS.length;
12676        for (int ip=0; ip<NP; ip++) {
12677            final PackageParser.NewPermissionInfo npi
12678                    = PackageParser.NEW_PERMISSIONS[ip];
12679            if (npi.name.equals(perm)
12680                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12681                allowed = true;
12682                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12683                        + pkg.packageName);
12684                break;
12685            }
12686        }
12687        return allowed;
12688    }
12689
12690    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12691            BasePermission bp, PermissionsState origPermissions) {
12692        boolean privilegedPermission = (bp.protectionLevel
12693                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12694        boolean privappPermissionsDisable =
12695                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12696        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12697        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12698        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12699                && !platformPackage && platformPermission) {
12700            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12701                    .getPrivAppPermissions(pkg.packageName);
12702            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12703            if (!whitelisted) {
12704                Slog.w(TAG, "Privileged permission " + perm + " for package "
12705                        + pkg.packageName + " - not in privapp-permissions whitelist");
12706                // Only report violations for apps on system image
12707                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12708                    if (mPrivappPermissionsViolations == null) {
12709                        mPrivappPermissionsViolations = new ArraySet<>();
12710                    }
12711                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12712                }
12713                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12714                    return false;
12715                }
12716            }
12717        }
12718        boolean allowed = (compareSignatures(
12719                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12720                        == PackageManager.SIGNATURE_MATCH)
12721                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12722                        == PackageManager.SIGNATURE_MATCH);
12723        if (!allowed && privilegedPermission) {
12724            if (isSystemApp(pkg)) {
12725                // For updated system applications, a system permission
12726                // is granted only if it had been defined by the original application.
12727                if (pkg.isUpdatedSystemApp()) {
12728                    final PackageSetting sysPs = mSettings
12729                            .getDisabledSystemPkgLPr(pkg.packageName);
12730                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12731                        // If the original was granted this permission, we take
12732                        // that grant decision as read and propagate it to the
12733                        // update.
12734                        if (sysPs.isPrivileged()) {
12735                            allowed = true;
12736                        }
12737                    } else {
12738                        // The system apk may have been updated with an older
12739                        // version of the one on the data partition, but which
12740                        // granted a new system permission that it didn't have
12741                        // before.  In this case we do want to allow the app to
12742                        // now get the new permission if the ancestral apk is
12743                        // privileged to get it.
12744                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12745                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12746                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12747                                    allowed = true;
12748                                    break;
12749                                }
12750                            }
12751                        }
12752                        // Also if a privileged parent package on the system image or any of
12753                        // its children requested a privileged permission, the updated child
12754                        // packages can also get the permission.
12755                        if (pkg.parentPackage != null) {
12756                            final PackageSetting disabledSysParentPs = mSettings
12757                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12758                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12759                                    && disabledSysParentPs.isPrivileged()) {
12760                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12761                                    allowed = true;
12762                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12763                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12764                                    for (int i = 0; i < count; i++) {
12765                                        PackageParser.Package disabledSysChildPkg =
12766                                                disabledSysParentPs.pkg.childPackages.get(i);
12767                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12768                                                perm)) {
12769                                            allowed = true;
12770                                            break;
12771                                        }
12772                                    }
12773                                }
12774                            }
12775                        }
12776                    }
12777                } else {
12778                    allowed = isPrivilegedApp(pkg);
12779                }
12780            }
12781        }
12782        if (!allowed) {
12783            if (!allowed && (bp.protectionLevel
12784                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12785                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12786                // If this was a previously normal/dangerous permission that got moved
12787                // to a system permission as part of the runtime permission redesign, then
12788                // we still want to blindly grant it to old apps.
12789                allowed = true;
12790            }
12791            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12792                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12793                // If this permission is to be granted to the system installer and
12794                // this app is an installer, then it gets the permission.
12795                allowed = true;
12796            }
12797            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12798                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12799                // If this permission is to be granted to the system verifier and
12800                // this app is a verifier, then it gets the permission.
12801                allowed = true;
12802            }
12803            if (!allowed && (bp.protectionLevel
12804                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12805                    && isSystemApp(pkg)) {
12806                // Any pre-installed system app is allowed to get this permission.
12807                allowed = true;
12808            }
12809            if (!allowed && (bp.protectionLevel
12810                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12811                // For development permissions, a development permission
12812                // is granted only if it was already granted.
12813                allowed = origPermissions.hasInstallPermission(perm);
12814            }
12815            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12816                    && pkg.packageName.equals(mSetupWizardPackage)) {
12817                // If this permission is to be granted to the system setup wizard and
12818                // this app is a setup wizard, then it gets the permission.
12819                allowed = true;
12820            }
12821        }
12822        return allowed;
12823    }
12824
12825    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12826        final int permCount = pkg.requestedPermissions.size();
12827        for (int j = 0; j < permCount; j++) {
12828            String requestedPermission = pkg.requestedPermissions.get(j);
12829            if (permission.equals(requestedPermission)) {
12830                return true;
12831            }
12832        }
12833        return false;
12834    }
12835
12836    final class ActivityIntentResolver
12837            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12838        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12839                boolean defaultOnly, int userId) {
12840            if (!sUserManager.exists(userId)) return null;
12841            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12842            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12843        }
12844
12845        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12846                int userId) {
12847            if (!sUserManager.exists(userId)) return null;
12848            mFlags = flags;
12849            return super.queryIntent(intent, resolvedType,
12850                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12851                    userId);
12852        }
12853
12854        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12855                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12856            if (!sUserManager.exists(userId)) return null;
12857            if (packageActivities == null) {
12858                return null;
12859            }
12860            mFlags = flags;
12861            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12862            final int N = packageActivities.size();
12863            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12864                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12865
12866            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12867            for (int i = 0; i < N; ++i) {
12868                intentFilters = packageActivities.get(i).intents;
12869                if (intentFilters != null && intentFilters.size() > 0) {
12870                    PackageParser.ActivityIntentInfo[] array =
12871                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12872                    intentFilters.toArray(array);
12873                    listCut.add(array);
12874                }
12875            }
12876            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12877        }
12878
12879        /**
12880         * Finds a privileged activity that matches the specified activity names.
12881         */
12882        private PackageParser.Activity findMatchingActivity(
12883                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12884            for (PackageParser.Activity sysActivity : activityList) {
12885                if (sysActivity.info.name.equals(activityInfo.name)) {
12886                    return sysActivity;
12887                }
12888                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12889                    return sysActivity;
12890                }
12891                if (sysActivity.info.targetActivity != null) {
12892                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12893                        return sysActivity;
12894                    }
12895                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12896                        return sysActivity;
12897                    }
12898                }
12899            }
12900            return null;
12901        }
12902
12903        public class IterGenerator<E> {
12904            public Iterator<E> generate(ActivityIntentInfo info) {
12905                return null;
12906            }
12907        }
12908
12909        public class ActionIterGenerator extends IterGenerator<String> {
12910            @Override
12911            public Iterator<String> generate(ActivityIntentInfo info) {
12912                return info.actionsIterator();
12913            }
12914        }
12915
12916        public class CategoriesIterGenerator extends IterGenerator<String> {
12917            @Override
12918            public Iterator<String> generate(ActivityIntentInfo info) {
12919                return info.categoriesIterator();
12920            }
12921        }
12922
12923        public class SchemesIterGenerator extends IterGenerator<String> {
12924            @Override
12925            public Iterator<String> generate(ActivityIntentInfo info) {
12926                return info.schemesIterator();
12927            }
12928        }
12929
12930        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12931            @Override
12932            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12933                return info.authoritiesIterator();
12934            }
12935        }
12936
12937        /**
12938         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12939         * MODIFIED. Do not pass in a list that should not be changed.
12940         */
12941        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12942                IterGenerator<T> generator, Iterator<T> searchIterator) {
12943            // loop through the set of actions; every one must be found in the intent filter
12944            while (searchIterator.hasNext()) {
12945                // we must have at least one filter in the list to consider a match
12946                if (intentList.size() == 0) {
12947                    break;
12948                }
12949
12950                final T searchAction = searchIterator.next();
12951
12952                // loop through the set of intent filters
12953                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12954                while (intentIter.hasNext()) {
12955                    final ActivityIntentInfo intentInfo = intentIter.next();
12956                    boolean selectionFound = false;
12957
12958                    // loop through the intent filter's selection criteria; at least one
12959                    // of them must match the searched criteria
12960                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12961                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12962                        final T intentSelection = intentSelectionIter.next();
12963                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12964                            selectionFound = true;
12965                            break;
12966                        }
12967                    }
12968
12969                    // the selection criteria wasn't found in this filter's set; this filter
12970                    // is not a potential match
12971                    if (!selectionFound) {
12972                        intentIter.remove();
12973                    }
12974                }
12975            }
12976        }
12977
12978        private boolean isProtectedAction(ActivityIntentInfo filter) {
12979            final Iterator<String> actionsIter = filter.actionsIterator();
12980            while (actionsIter != null && actionsIter.hasNext()) {
12981                final String filterAction = actionsIter.next();
12982                if (PROTECTED_ACTIONS.contains(filterAction)) {
12983                    return true;
12984                }
12985            }
12986            return false;
12987        }
12988
12989        /**
12990         * Adjusts the priority of the given intent filter according to policy.
12991         * <p>
12992         * <ul>
12993         * <li>The priority for non privileged applications is capped to '0'</li>
12994         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12995         * <li>The priority for unbundled updates to privileged applications is capped to the
12996         *      priority defined on the system partition</li>
12997         * </ul>
12998         * <p>
12999         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13000         * allowed to obtain any priority on any action.
13001         */
13002        private void adjustPriority(
13003                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13004            // nothing to do; priority is fine as-is
13005            if (intent.getPriority() <= 0) {
13006                return;
13007            }
13008
13009            final ActivityInfo activityInfo = intent.activity.info;
13010            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13011
13012            final boolean privilegedApp =
13013                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13014            if (!privilegedApp) {
13015                // non-privileged applications can never define a priority >0
13016                if (DEBUG_FILTERS) {
13017                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13018                            + " package: " + applicationInfo.packageName
13019                            + " activity: " + intent.activity.className
13020                            + " origPrio: " + intent.getPriority());
13021                }
13022                intent.setPriority(0);
13023                return;
13024            }
13025
13026            if (systemActivities == null) {
13027                // the system package is not disabled; we're parsing the system partition
13028                if (isProtectedAction(intent)) {
13029                    if (mDeferProtectedFilters) {
13030                        // We can't deal with these just yet. No component should ever obtain a
13031                        // >0 priority for a protected actions, with ONE exception -- the setup
13032                        // wizard. The setup wizard, however, cannot be known until we're able to
13033                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13034                        // until all intent filters have been processed. Chicken, meet egg.
13035                        // Let the filter temporarily have a high priority and rectify the
13036                        // priorities after all system packages have been scanned.
13037                        mProtectedFilters.add(intent);
13038                        if (DEBUG_FILTERS) {
13039                            Slog.i(TAG, "Protected action; save for later;"
13040                                    + " package: " + applicationInfo.packageName
13041                                    + " activity: " + intent.activity.className
13042                                    + " origPrio: " + intent.getPriority());
13043                        }
13044                        return;
13045                    } else {
13046                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13047                            Slog.i(TAG, "No setup wizard;"
13048                                + " All protected intents capped to priority 0");
13049                        }
13050                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13051                            if (DEBUG_FILTERS) {
13052                                Slog.i(TAG, "Found setup wizard;"
13053                                    + " allow priority " + intent.getPriority() + ";"
13054                                    + " package: " + intent.activity.info.packageName
13055                                    + " activity: " + intent.activity.className
13056                                    + " priority: " + intent.getPriority());
13057                            }
13058                            // setup wizard gets whatever it wants
13059                            return;
13060                        }
13061                        if (DEBUG_FILTERS) {
13062                            Slog.i(TAG, "Protected action; cap priority to 0;"
13063                                    + " package: " + intent.activity.info.packageName
13064                                    + " activity: " + intent.activity.className
13065                                    + " origPrio: " + intent.getPriority());
13066                        }
13067                        intent.setPriority(0);
13068                        return;
13069                    }
13070                }
13071                // privileged apps on the system image get whatever priority they request
13072                return;
13073            }
13074
13075            // privileged app unbundled update ... try to find the same activity
13076            final PackageParser.Activity foundActivity =
13077                    findMatchingActivity(systemActivities, activityInfo);
13078            if (foundActivity == null) {
13079                // this is a new activity; it cannot obtain >0 priority
13080                if (DEBUG_FILTERS) {
13081                    Slog.i(TAG, "New activity; cap priority to 0;"
13082                            + " package: " + applicationInfo.packageName
13083                            + " activity: " + intent.activity.className
13084                            + " origPrio: " + intent.getPriority());
13085                }
13086                intent.setPriority(0);
13087                return;
13088            }
13089
13090            // found activity, now check for filter equivalence
13091
13092            // a shallow copy is enough; we modify the list, not its contents
13093            final List<ActivityIntentInfo> intentListCopy =
13094                    new ArrayList<>(foundActivity.intents);
13095            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13096
13097            // find matching action subsets
13098            final Iterator<String> actionsIterator = intent.actionsIterator();
13099            if (actionsIterator != null) {
13100                getIntentListSubset(
13101                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13102                if (intentListCopy.size() == 0) {
13103                    // no more intents to match; we're not equivalent
13104                    if (DEBUG_FILTERS) {
13105                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13106                                + " package: " + applicationInfo.packageName
13107                                + " activity: " + intent.activity.className
13108                                + " origPrio: " + intent.getPriority());
13109                    }
13110                    intent.setPriority(0);
13111                    return;
13112                }
13113            }
13114
13115            // find matching category subsets
13116            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13117            if (categoriesIterator != null) {
13118                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13119                        categoriesIterator);
13120                if (intentListCopy.size() == 0) {
13121                    // no more intents to match; we're not equivalent
13122                    if (DEBUG_FILTERS) {
13123                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13124                                + " package: " + applicationInfo.packageName
13125                                + " activity: " + intent.activity.className
13126                                + " origPrio: " + intent.getPriority());
13127                    }
13128                    intent.setPriority(0);
13129                    return;
13130                }
13131            }
13132
13133            // find matching schemes subsets
13134            final Iterator<String> schemesIterator = intent.schemesIterator();
13135            if (schemesIterator != null) {
13136                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13137                        schemesIterator);
13138                if (intentListCopy.size() == 0) {
13139                    // no more intents to match; we're not equivalent
13140                    if (DEBUG_FILTERS) {
13141                        Slog.i(TAG, "Mismatched scheme; 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
13151            // find matching authorities subsets
13152            final Iterator<IntentFilter.AuthorityEntry>
13153                    authoritiesIterator = intent.authoritiesIterator();
13154            if (authoritiesIterator != null) {
13155                getIntentListSubset(intentListCopy,
13156                        new AuthoritiesIterGenerator(),
13157                        authoritiesIterator);
13158                if (intentListCopy.size() == 0) {
13159                    // no more intents to match; we're not equivalent
13160                    if (DEBUG_FILTERS) {
13161                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13162                                + " package: " + applicationInfo.packageName
13163                                + " activity: " + intent.activity.className
13164                                + " origPrio: " + intent.getPriority());
13165                    }
13166                    intent.setPriority(0);
13167                    return;
13168                }
13169            }
13170
13171            // we found matching filter(s); app gets the max priority of all intents
13172            int cappedPriority = 0;
13173            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13174                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13175            }
13176            if (intent.getPriority() > cappedPriority) {
13177                if (DEBUG_FILTERS) {
13178                    Slog.i(TAG, "Found matching filter(s);"
13179                            + " cap priority to " + cappedPriority + ";"
13180                            + " package: " + applicationInfo.packageName
13181                            + " activity: " + intent.activity.className
13182                            + " origPrio: " + intent.getPriority());
13183                }
13184                intent.setPriority(cappedPriority);
13185                return;
13186            }
13187            // all this for nothing; the requested priority was <= what was on the system
13188        }
13189
13190        public final void addActivity(PackageParser.Activity a, String type) {
13191            mActivities.put(a.getComponentName(), a);
13192            if (DEBUG_SHOW_INFO)
13193                Log.v(
13194                TAG, "  " + type + " " +
13195                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13196            if (DEBUG_SHOW_INFO)
13197                Log.v(TAG, "    Class=" + a.info.name);
13198            final int NI = a.intents.size();
13199            for (int j=0; j<NI; j++) {
13200                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13201                if ("activity".equals(type)) {
13202                    final PackageSetting ps =
13203                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13204                    final List<PackageParser.Activity> systemActivities =
13205                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13206                    adjustPriority(systemActivities, intent);
13207                }
13208                if (DEBUG_SHOW_INFO) {
13209                    Log.v(TAG, "    IntentFilter:");
13210                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13211                }
13212                if (!intent.debugCheck()) {
13213                    Log.w(TAG, "==> For Activity " + a.info.name);
13214                }
13215                addFilter(intent);
13216            }
13217        }
13218
13219        public final void removeActivity(PackageParser.Activity a, String type) {
13220            mActivities.remove(a.getComponentName());
13221            if (DEBUG_SHOW_INFO) {
13222                Log.v(TAG, "  " + type + " "
13223                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13224                                : a.info.name) + ":");
13225                Log.v(TAG, "    Class=" + a.info.name);
13226            }
13227            final int NI = a.intents.size();
13228            for (int j=0; j<NI; j++) {
13229                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13230                if (DEBUG_SHOW_INFO) {
13231                    Log.v(TAG, "    IntentFilter:");
13232                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13233                }
13234                removeFilter(intent);
13235            }
13236        }
13237
13238        @Override
13239        protected boolean allowFilterResult(
13240                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13241            ActivityInfo filterAi = filter.activity.info;
13242            for (int i=dest.size()-1; i>=0; i--) {
13243                ActivityInfo destAi = dest.get(i).activityInfo;
13244                if (destAi.name == filterAi.name
13245                        && destAi.packageName == filterAi.packageName) {
13246                    return false;
13247                }
13248            }
13249            return true;
13250        }
13251
13252        @Override
13253        protected ActivityIntentInfo[] newArray(int size) {
13254            return new ActivityIntentInfo[size];
13255        }
13256
13257        @Override
13258        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13259            if (!sUserManager.exists(userId)) return true;
13260            PackageParser.Package p = filter.activity.owner;
13261            if (p != null) {
13262                PackageSetting ps = (PackageSetting)p.mExtras;
13263                if (ps != null) {
13264                    // System apps are never considered stopped for purposes of
13265                    // filtering, because there may be no way for the user to
13266                    // actually re-launch them.
13267                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13268                            && ps.getStopped(userId);
13269                }
13270            }
13271            return false;
13272        }
13273
13274        @Override
13275        protected boolean isPackageForFilter(String packageName,
13276                PackageParser.ActivityIntentInfo info) {
13277            return packageName.equals(info.activity.owner.packageName);
13278        }
13279
13280        @Override
13281        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13282                int match, int userId) {
13283            if (!sUserManager.exists(userId)) return null;
13284            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13285                return null;
13286            }
13287            final PackageParser.Activity activity = info.activity;
13288            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13289            if (ps == null) {
13290                return null;
13291            }
13292            final PackageUserState userState = ps.readUserState(userId);
13293            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
13294            if (ai == null) {
13295                return null;
13296            }
13297            final boolean matchExplicitlyVisibleOnly =
13298                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13299            final boolean matchVisibleToInstantApp =
13300                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13301            final boolean componentVisible =
13302                    matchVisibleToInstantApp
13303                    && info.isVisibleToInstantApp()
13304                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13305            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13306            // throw out filters that aren't visible to ephemeral apps
13307            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13308                return null;
13309            }
13310            // throw out instant app filters if we're not explicitly requesting them
13311            if (!matchInstantApp && userState.instantApp) {
13312                return null;
13313            }
13314            // throw out instant app filters if updates are available; will trigger
13315            // instant app resolution
13316            if (userState.instantApp && ps.isUpdateAvailable()) {
13317                return null;
13318            }
13319            final ResolveInfo res = new ResolveInfo();
13320            res.activityInfo = ai;
13321            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13322                res.filter = info;
13323            }
13324            if (info != null) {
13325                res.handleAllWebDataURI = info.handleAllWebDataURI();
13326            }
13327            res.priority = info.getPriority();
13328            res.preferredOrder = activity.owner.mPreferredOrder;
13329            //System.out.println("Result: " + res.activityInfo.className +
13330            //                   " = " + res.priority);
13331            res.match = match;
13332            res.isDefault = info.hasDefault;
13333            res.labelRes = info.labelRes;
13334            res.nonLocalizedLabel = info.nonLocalizedLabel;
13335            if (userNeedsBadging(userId)) {
13336                res.noResourceId = true;
13337            } else {
13338                res.icon = info.icon;
13339            }
13340            res.iconResourceId = info.icon;
13341            res.system = res.activityInfo.applicationInfo.isSystemApp();
13342            res.isInstantAppAvailable = userState.instantApp;
13343            return res;
13344        }
13345
13346        @Override
13347        protected void sortResults(List<ResolveInfo> results) {
13348            Collections.sort(results, mResolvePrioritySorter);
13349        }
13350
13351        @Override
13352        protected void dumpFilter(PrintWriter out, String prefix,
13353                PackageParser.ActivityIntentInfo filter) {
13354            out.print(prefix); out.print(
13355                    Integer.toHexString(System.identityHashCode(filter.activity)));
13356                    out.print(' ');
13357                    filter.activity.printComponentShortName(out);
13358                    out.print(" filter ");
13359                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13360        }
13361
13362        @Override
13363        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13364            return filter.activity;
13365        }
13366
13367        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13368            PackageParser.Activity activity = (PackageParser.Activity)label;
13369            out.print(prefix); out.print(
13370                    Integer.toHexString(System.identityHashCode(activity)));
13371                    out.print(' ');
13372                    activity.printComponentShortName(out);
13373            if (count > 1) {
13374                out.print(" ("); out.print(count); out.print(" filters)");
13375            }
13376            out.println();
13377        }
13378
13379        // Keys are String (activity class name), values are Activity.
13380        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13381                = new ArrayMap<ComponentName, PackageParser.Activity>();
13382        private int mFlags;
13383    }
13384
13385    private final class ServiceIntentResolver
13386            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13387        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13388                boolean defaultOnly, int userId) {
13389            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13390            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13391        }
13392
13393        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13394                int userId) {
13395            if (!sUserManager.exists(userId)) return null;
13396            mFlags = flags;
13397            return super.queryIntent(intent, resolvedType,
13398                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13399                    userId);
13400        }
13401
13402        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13403                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13404            if (!sUserManager.exists(userId)) return null;
13405            if (packageServices == null) {
13406                return null;
13407            }
13408            mFlags = flags;
13409            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13410            final int N = packageServices.size();
13411            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13412                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13413
13414            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13415            for (int i = 0; i < N; ++i) {
13416                intentFilters = packageServices.get(i).intents;
13417                if (intentFilters != null && intentFilters.size() > 0) {
13418                    PackageParser.ServiceIntentInfo[] array =
13419                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13420                    intentFilters.toArray(array);
13421                    listCut.add(array);
13422                }
13423            }
13424            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13425        }
13426
13427        public final void addService(PackageParser.Service s) {
13428            mServices.put(s.getComponentName(), s);
13429            if (DEBUG_SHOW_INFO) {
13430                Log.v(TAG, "  "
13431                        + (s.info.nonLocalizedLabel != null
13432                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13433                Log.v(TAG, "    Class=" + s.info.name);
13434            }
13435            final int NI = s.intents.size();
13436            int j;
13437            for (j=0; j<NI; j++) {
13438                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13439                if (DEBUG_SHOW_INFO) {
13440                    Log.v(TAG, "    IntentFilter:");
13441                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13442                }
13443                if (!intent.debugCheck()) {
13444                    Log.w(TAG, "==> For Service " + s.info.name);
13445                }
13446                addFilter(intent);
13447            }
13448        }
13449
13450        public final void removeService(PackageParser.Service s) {
13451            mServices.remove(s.getComponentName());
13452            if (DEBUG_SHOW_INFO) {
13453                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13454                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13455                Log.v(TAG, "    Class=" + s.info.name);
13456            }
13457            final int NI = s.intents.size();
13458            int j;
13459            for (j=0; j<NI; j++) {
13460                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13461                if (DEBUG_SHOW_INFO) {
13462                    Log.v(TAG, "    IntentFilter:");
13463                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13464                }
13465                removeFilter(intent);
13466            }
13467        }
13468
13469        @Override
13470        protected boolean allowFilterResult(
13471                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13472            ServiceInfo filterSi = filter.service.info;
13473            for (int i=dest.size()-1; i>=0; i--) {
13474                ServiceInfo destAi = dest.get(i).serviceInfo;
13475                if (destAi.name == filterSi.name
13476                        && destAi.packageName == filterSi.packageName) {
13477                    return false;
13478                }
13479            }
13480            return true;
13481        }
13482
13483        @Override
13484        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13485            return new PackageParser.ServiceIntentInfo[size];
13486        }
13487
13488        @Override
13489        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13490            if (!sUserManager.exists(userId)) return true;
13491            PackageParser.Package p = filter.service.owner;
13492            if (p != null) {
13493                PackageSetting ps = (PackageSetting)p.mExtras;
13494                if (ps != null) {
13495                    // System apps are never considered stopped for purposes of
13496                    // filtering, because there may be no way for the user to
13497                    // actually re-launch them.
13498                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13499                            && ps.getStopped(userId);
13500                }
13501            }
13502            return false;
13503        }
13504
13505        @Override
13506        protected boolean isPackageForFilter(String packageName,
13507                PackageParser.ServiceIntentInfo info) {
13508            return packageName.equals(info.service.owner.packageName);
13509        }
13510
13511        @Override
13512        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13513                int match, int userId) {
13514            if (!sUserManager.exists(userId)) return null;
13515            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13516            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13517                return null;
13518            }
13519            final PackageParser.Service service = info.service;
13520            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13521            if (ps == null) {
13522                return null;
13523            }
13524            final PackageUserState userState = ps.readUserState(userId);
13525            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13526                    userState, userId);
13527            if (si == null) {
13528                return null;
13529            }
13530            final boolean matchVisibleToInstantApp =
13531                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13532            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13533            // throw out filters that aren't visible to ephemeral apps
13534            if (matchVisibleToInstantApp
13535                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13536                return null;
13537            }
13538            // throw out ephemeral filters if we're not explicitly requesting them
13539            if (!isInstantApp && userState.instantApp) {
13540                return null;
13541            }
13542            // throw out instant app filters if updates are available; will trigger
13543            // instant app resolution
13544            if (userState.instantApp && ps.isUpdateAvailable()) {
13545                return null;
13546            }
13547            final ResolveInfo res = new ResolveInfo();
13548            res.serviceInfo = si;
13549            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13550                res.filter = filter;
13551            }
13552            res.priority = info.getPriority();
13553            res.preferredOrder = service.owner.mPreferredOrder;
13554            res.match = match;
13555            res.isDefault = info.hasDefault;
13556            res.labelRes = info.labelRes;
13557            res.nonLocalizedLabel = info.nonLocalizedLabel;
13558            res.icon = info.icon;
13559            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13560            return res;
13561        }
13562
13563        @Override
13564        protected void sortResults(List<ResolveInfo> results) {
13565            Collections.sort(results, mResolvePrioritySorter);
13566        }
13567
13568        @Override
13569        protected void dumpFilter(PrintWriter out, String prefix,
13570                PackageParser.ServiceIntentInfo filter) {
13571            out.print(prefix); out.print(
13572                    Integer.toHexString(System.identityHashCode(filter.service)));
13573                    out.print(' ');
13574                    filter.service.printComponentShortName(out);
13575                    out.print(" filter ");
13576                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13577        }
13578
13579        @Override
13580        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13581            return filter.service;
13582        }
13583
13584        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13585            PackageParser.Service service = (PackageParser.Service)label;
13586            out.print(prefix); out.print(
13587                    Integer.toHexString(System.identityHashCode(service)));
13588                    out.print(' ');
13589                    service.printComponentShortName(out);
13590            if (count > 1) {
13591                out.print(" ("); out.print(count); out.print(" filters)");
13592            }
13593            out.println();
13594        }
13595
13596//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13597//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13598//            final List<ResolveInfo> retList = Lists.newArrayList();
13599//            while (i.hasNext()) {
13600//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13601//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13602//                    retList.add(resolveInfo);
13603//                }
13604//            }
13605//            return retList;
13606//        }
13607
13608        // Keys are String (activity class name), values are Activity.
13609        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13610                = new ArrayMap<ComponentName, PackageParser.Service>();
13611        private int mFlags;
13612    }
13613
13614    private final class ProviderIntentResolver
13615            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13616        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13617                boolean defaultOnly, int userId) {
13618            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13619            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13620        }
13621
13622        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13623                int userId) {
13624            if (!sUserManager.exists(userId))
13625                return null;
13626            mFlags = flags;
13627            return super.queryIntent(intent, resolvedType,
13628                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13629                    userId);
13630        }
13631
13632        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13633                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13634            if (!sUserManager.exists(userId))
13635                return null;
13636            if (packageProviders == null) {
13637                return null;
13638            }
13639            mFlags = flags;
13640            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13641            final int N = packageProviders.size();
13642            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13643                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13644
13645            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13646            for (int i = 0; i < N; ++i) {
13647                intentFilters = packageProviders.get(i).intents;
13648                if (intentFilters != null && intentFilters.size() > 0) {
13649                    PackageParser.ProviderIntentInfo[] array =
13650                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13651                    intentFilters.toArray(array);
13652                    listCut.add(array);
13653                }
13654            }
13655            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13656        }
13657
13658        public final void addProvider(PackageParser.Provider p) {
13659            if (mProviders.containsKey(p.getComponentName())) {
13660                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13661                return;
13662            }
13663
13664            mProviders.put(p.getComponentName(), p);
13665            if (DEBUG_SHOW_INFO) {
13666                Log.v(TAG, "  "
13667                        + (p.info.nonLocalizedLabel != null
13668                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13669                Log.v(TAG, "    Class=" + p.info.name);
13670            }
13671            final int NI = p.intents.size();
13672            int j;
13673            for (j = 0; j < NI; j++) {
13674                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13675                if (DEBUG_SHOW_INFO) {
13676                    Log.v(TAG, "    IntentFilter:");
13677                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13678                }
13679                if (!intent.debugCheck()) {
13680                    Log.w(TAG, "==> For Provider " + p.info.name);
13681                }
13682                addFilter(intent);
13683            }
13684        }
13685
13686        public final void removeProvider(PackageParser.Provider p) {
13687            mProviders.remove(p.getComponentName());
13688            if (DEBUG_SHOW_INFO) {
13689                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13690                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13691                Log.v(TAG, "    Class=" + p.info.name);
13692            }
13693            final int NI = p.intents.size();
13694            int j;
13695            for (j = 0; j < NI; j++) {
13696                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13697                if (DEBUG_SHOW_INFO) {
13698                    Log.v(TAG, "    IntentFilter:");
13699                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13700                }
13701                removeFilter(intent);
13702            }
13703        }
13704
13705        @Override
13706        protected boolean allowFilterResult(
13707                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13708            ProviderInfo filterPi = filter.provider.info;
13709            for (int i = dest.size() - 1; i >= 0; i--) {
13710                ProviderInfo destPi = dest.get(i).providerInfo;
13711                if (destPi.name == filterPi.name
13712                        && destPi.packageName == filterPi.packageName) {
13713                    return false;
13714                }
13715            }
13716            return true;
13717        }
13718
13719        @Override
13720        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13721            return new PackageParser.ProviderIntentInfo[size];
13722        }
13723
13724        @Override
13725        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13726            if (!sUserManager.exists(userId))
13727                return true;
13728            PackageParser.Package p = filter.provider.owner;
13729            if (p != null) {
13730                PackageSetting ps = (PackageSetting) p.mExtras;
13731                if (ps != null) {
13732                    // System apps are never considered stopped for purposes of
13733                    // filtering, because there may be no way for the user to
13734                    // actually re-launch them.
13735                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13736                            && ps.getStopped(userId);
13737                }
13738            }
13739            return false;
13740        }
13741
13742        @Override
13743        protected boolean isPackageForFilter(String packageName,
13744                PackageParser.ProviderIntentInfo info) {
13745            return packageName.equals(info.provider.owner.packageName);
13746        }
13747
13748        @Override
13749        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13750                int match, int userId) {
13751            if (!sUserManager.exists(userId))
13752                return null;
13753            final PackageParser.ProviderIntentInfo info = filter;
13754            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13755                return null;
13756            }
13757            final PackageParser.Provider provider = info.provider;
13758            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13759            if (ps == null) {
13760                return null;
13761            }
13762            final PackageUserState userState = ps.readUserState(userId);
13763            final boolean matchVisibleToInstantApp =
13764                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13765            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13766            // throw out filters that aren't visible to instant applications
13767            if (matchVisibleToInstantApp
13768                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13769                return null;
13770            }
13771            // throw out instant application filters if we're not explicitly requesting them
13772            if (!isInstantApp && userState.instantApp) {
13773                return null;
13774            }
13775            // throw out instant application filters if updates are available; will trigger
13776            // instant application resolution
13777            if (userState.instantApp && ps.isUpdateAvailable()) {
13778                return null;
13779            }
13780            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13781                    userState, userId);
13782            if (pi == null) {
13783                return null;
13784            }
13785            final ResolveInfo res = new ResolveInfo();
13786            res.providerInfo = pi;
13787            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13788                res.filter = filter;
13789            }
13790            res.priority = info.getPriority();
13791            res.preferredOrder = provider.owner.mPreferredOrder;
13792            res.match = match;
13793            res.isDefault = info.hasDefault;
13794            res.labelRes = info.labelRes;
13795            res.nonLocalizedLabel = info.nonLocalizedLabel;
13796            res.icon = info.icon;
13797            res.system = res.providerInfo.applicationInfo.isSystemApp();
13798            return res;
13799        }
13800
13801        @Override
13802        protected void sortResults(List<ResolveInfo> results) {
13803            Collections.sort(results, mResolvePrioritySorter);
13804        }
13805
13806        @Override
13807        protected void dumpFilter(PrintWriter out, String prefix,
13808                PackageParser.ProviderIntentInfo filter) {
13809            out.print(prefix);
13810            out.print(
13811                    Integer.toHexString(System.identityHashCode(filter.provider)));
13812            out.print(' ');
13813            filter.provider.printComponentShortName(out);
13814            out.print(" filter ");
13815            out.println(Integer.toHexString(System.identityHashCode(filter)));
13816        }
13817
13818        @Override
13819        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13820            return filter.provider;
13821        }
13822
13823        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13824            PackageParser.Provider provider = (PackageParser.Provider)label;
13825            out.print(prefix); out.print(
13826                    Integer.toHexString(System.identityHashCode(provider)));
13827                    out.print(' ');
13828                    provider.printComponentShortName(out);
13829            if (count > 1) {
13830                out.print(" ("); out.print(count); out.print(" filters)");
13831            }
13832            out.println();
13833        }
13834
13835        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13836                = new ArrayMap<ComponentName, PackageParser.Provider>();
13837        private int mFlags;
13838    }
13839
13840    static final class EphemeralIntentResolver
13841            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13842        /**
13843         * The result that has the highest defined order. Ordering applies on a
13844         * per-package basis. Mapping is from package name to Pair of order and
13845         * EphemeralResolveInfo.
13846         * <p>
13847         * NOTE: This is implemented as a field variable for convenience and efficiency.
13848         * By having a field variable, we're able to track filter ordering as soon as
13849         * a non-zero order is defined. Otherwise, multiple loops across the result set
13850         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13851         * this needs to be contained entirely within {@link #filterResults}.
13852         */
13853        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13854
13855        @Override
13856        protected AuxiliaryResolveInfo[] newArray(int size) {
13857            return new AuxiliaryResolveInfo[size];
13858        }
13859
13860        @Override
13861        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13862            return true;
13863        }
13864
13865        @Override
13866        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13867                int userId) {
13868            if (!sUserManager.exists(userId)) {
13869                return null;
13870            }
13871            final String packageName = responseObj.resolveInfo.getPackageName();
13872            final Integer order = responseObj.getOrder();
13873            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13874                    mOrderResult.get(packageName);
13875            // ordering is enabled and this item's order isn't high enough
13876            if (lastOrderResult != null && lastOrderResult.first >= order) {
13877                return null;
13878            }
13879            final InstantAppResolveInfo res = responseObj.resolveInfo;
13880            if (order > 0) {
13881                // non-zero order, enable ordering
13882                mOrderResult.put(packageName, new Pair<>(order, res));
13883            }
13884            return responseObj;
13885        }
13886
13887        @Override
13888        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13889            // only do work if ordering is enabled [most of the time it won't be]
13890            if (mOrderResult.size() == 0) {
13891                return;
13892            }
13893            int resultSize = results.size();
13894            for (int i = 0; i < resultSize; i++) {
13895                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13896                final String packageName = info.getPackageName();
13897                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13898                if (savedInfo == null) {
13899                    // package doesn't having ordering
13900                    continue;
13901                }
13902                if (savedInfo.second == info) {
13903                    // circled back to the highest ordered item; remove from order list
13904                    mOrderResult.remove(savedInfo);
13905                    if (mOrderResult.size() == 0) {
13906                        // no more ordered items
13907                        break;
13908                    }
13909                    continue;
13910                }
13911                // item has a worse order, remove it from the result list
13912                results.remove(i);
13913                resultSize--;
13914                i--;
13915            }
13916        }
13917    }
13918
13919    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13920            new Comparator<ResolveInfo>() {
13921        public int compare(ResolveInfo r1, ResolveInfo r2) {
13922            int v1 = r1.priority;
13923            int v2 = r2.priority;
13924            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13925            if (v1 != v2) {
13926                return (v1 > v2) ? -1 : 1;
13927            }
13928            v1 = r1.preferredOrder;
13929            v2 = r2.preferredOrder;
13930            if (v1 != v2) {
13931                return (v1 > v2) ? -1 : 1;
13932            }
13933            if (r1.isDefault != r2.isDefault) {
13934                return r1.isDefault ? -1 : 1;
13935            }
13936            v1 = r1.match;
13937            v2 = r2.match;
13938            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13939            if (v1 != v2) {
13940                return (v1 > v2) ? -1 : 1;
13941            }
13942            if (r1.system != r2.system) {
13943                return r1.system ? -1 : 1;
13944            }
13945            if (r1.activityInfo != null) {
13946                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13947            }
13948            if (r1.serviceInfo != null) {
13949                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13950            }
13951            if (r1.providerInfo != null) {
13952                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13953            }
13954            return 0;
13955        }
13956    };
13957
13958    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13959            new Comparator<ProviderInfo>() {
13960        public int compare(ProviderInfo p1, ProviderInfo p2) {
13961            final int v1 = p1.initOrder;
13962            final int v2 = p2.initOrder;
13963            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13964        }
13965    };
13966
13967    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13968            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13969            final int[] userIds) {
13970        mHandler.post(new Runnable() {
13971            @Override
13972            public void run() {
13973                try {
13974                    final IActivityManager am = ActivityManager.getService();
13975                    if (am == null) return;
13976                    final int[] resolvedUserIds;
13977                    if (userIds == null) {
13978                        resolvedUserIds = am.getRunningUserIds();
13979                    } else {
13980                        resolvedUserIds = userIds;
13981                    }
13982                    for (int id : resolvedUserIds) {
13983                        final Intent intent = new Intent(action,
13984                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13985                        if (extras != null) {
13986                            intent.putExtras(extras);
13987                        }
13988                        if (targetPkg != null) {
13989                            intent.setPackage(targetPkg);
13990                        }
13991                        // Modify the UID when posting to other users
13992                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13993                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13994                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13995                            intent.putExtra(Intent.EXTRA_UID, uid);
13996                        }
13997                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13998                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13999                        if (DEBUG_BROADCASTS) {
14000                            RuntimeException here = new RuntimeException("here");
14001                            here.fillInStackTrace();
14002                            Slog.d(TAG, "Sending to user " + id + ": "
14003                                    + intent.toShortString(false, true, false, false)
14004                                    + " " + intent.getExtras(), here);
14005                        }
14006                        am.broadcastIntent(null, intent, null, finishedReceiver,
14007                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14008                                null, finishedReceiver != null, false, id);
14009                    }
14010                } catch (RemoteException ex) {
14011                }
14012            }
14013        });
14014    }
14015
14016    /**
14017     * Check if the external storage media is available. This is true if there
14018     * is a mounted external storage medium or if the external storage is
14019     * emulated.
14020     */
14021    private boolean isExternalMediaAvailable() {
14022        return mMediaMounted || Environment.isExternalStorageEmulated();
14023    }
14024
14025    @Override
14026    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14027        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14028            return null;
14029        }
14030        // writer
14031        synchronized (mPackages) {
14032            if (!isExternalMediaAvailable()) {
14033                // If the external storage is no longer mounted at this point,
14034                // the caller may not have been able to delete all of this
14035                // packages files and can not delete any more.  Bail.
14036                return null;
14037            }
14038            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14039            if (lastPackage != null) {
14040                pkgs.remove(lastPackage);
14041            }
14042            if (pkgs.size() > 0) {
14043                return pkgs.get(0);
14044            }
14045        }
14046        return null;
14047    }
14048
14049    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14050        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14051                userId, andCode ? 1 : 0, packageName);
14052        if (mSystemReady) {
14053            msg.sendToTarget();
14054        } else {
14055            if (mPostSystemReadyMessages == null) {
14056                mPostSystemReadyMessages = new ArrayList<>();
14057            }
14058            mPostSystemReadyMessages.add(msg);
14059        }
14060    }
14061
14062    void startCleaningPackages() {
14063        // reader
14064        if (!isExternalMediaAvailable()) {
14065            return;
14066        }
14067        synchronized (mPackages) {
14068            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14069                return;
14070            }
14071        }
14072        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14073        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14074        IActivityManager am = ActivityManager.getService();
14075        if (am != null) {
14076            int dcsUid = -1;
14077            synchronized (mPackages) {
14078                if (!mDefaultContainerWhitelisted) {
14079                    mDefaultContainerWhitelisted = true;
14080                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14081                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14082                }
14083            }
14084            try {
14085                if (dcsUid > 0) {
14086                    am.backgroundWhitelistUid(dcsUid);
14087                }
14088                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14089                        UserHandle.USER_SYSTEM);
14090            } catch (RemoteException e) {
14091            }
14092        }
14093    }
14094
14095    @Override
14096    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14097            int installFlags, String installerPackageName, int userId) {
14098        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14099
14100        final int callingUid = Binder.getCallingUid();
14101        enforceCrossUserPermission(callingUid, userId,
14102                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14103
14104        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14105            try {
14106                if (observer != null) {
14107                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14108                }
14109            } catch (RemoteException re) {
14110            }
14111            return;
14112        }
14113
14114        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14115            installFlags |= PackageManager.INSTALL_FROM_ADB;
14116
14117        } else {
14118            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14119            // about installerPackageName.
14120
14121            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14122            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14123        }
14124
14125        UserHandle user;
14126        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14127            user = UserHandle.ALL;
14128        } else {
14129            user = new UserHandle(userId);
14130        }
14131
14132        // Only system components can circumvent runtime permissions when installing.
14133        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14134                && mContext.checkCallingOrSelfPermission(Manifest.permission
14135                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14136            throw new SecurityException("You need the "
14137                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14138                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14139        }
14140
14141        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14142                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14143            throw new IllegalArgumentException(
14144                    "New installs into ASEC containers no longer supported");
14145        }
14146
14147        final File originFile = new File(originPath);
14148        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14149
14150        final Message msg = mHandler.obtainMessage(INIT_COPY);
14151        final VerificationInfo verificationInfo = new VerificationInfo(
14152                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14153        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14154                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14155                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14156                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14157        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14158        msg.obj = params;
14159
14160        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14161                System.identityHashCode(msg.obj));
14162        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14163                System.identityHashCode(msg.obj));
14164
14165        mHandler.sendMessage(msg);
14166    }
14167
14168
14169    /**
14170     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14171     * it is acting on behalf on an enterprise or the user).
14172     *
14173     * Note that the ordering of the conditionals in this method is important. The checks we perform
14174     * are as follows, in this order:
14175     *
14176     * 1) If the install is being performed by a system app, we can trust the app to have set the
14177     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14178     *    what it is.
14179     * 2) If the install is being performed by a device or profile owner app, the install reason
14180     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14181     *    set the install reason correctly. If the app targets an older SDK version where install
14182     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14183     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14184     * 3) In all other cases, the install is being performed by a regular app that is neither part
14185     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14186     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14187     *    set to enterprise policy and if so, change it to unknown instead.
14188     */
14189    private int fixUpInstallReason(String installerPackageName, int installerUid,
14190            int installReason) {
14191        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14192                == PERMISSION_GRANTED) {
14193            // If the install is being performed by a system app, we trust that app to have set the
14194            // install reason correctly.
14195            return installReason;
14196        }
14197
14198        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14199            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14200        if (dpm != null) {
14201            ComponentName owner = null;
14202            try {
14203                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14204                if (owner == null) {
14205                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14206                }
14207            } catch (RemoteException e) {
14208            }
14209            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14210                // If the install is being performed by a device or profile owner, the install
14211                // reason should be enterprise policy.
14212                return PackageManager.INSTALL_REASON_POLICY;
14213            }
14214        }
14215
14216        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14217            // If the install is being performed by a regular app (i.e. neither system app nor
14218            // device or profile owner), we have no reason to believe that the app is acting on
14219            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14220            // change it to unknown instead.
14221            return PackageManager.INSTALL_REASON_UNKNOWN;
14222        }
14223
14224        // If the install is being performed by a regular app and the install reason was set to any
14225        // value but enterprise policy, leave the install reason unchanged.
14226        return installReason;
14227    }
14228
14229    void installStage(String packageName, File stagedDir, String stagedCid,
14230            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14231            String installerPackageName, int installerUid, UserHandle user,
14232            Certificate[][] certificates) {
14233        if (DEBUG_EPHEMERAL) {
14234            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14235                Slog.d(TAG, "Ephemeral install of " + packageName);
14236            }
14237        }
14238        final VerificationInfo verificationInfo = new VerificationInfo(
14239                sessionParams.originatingUri, sessionParams.referrerUri,
14240                sessionParams.originatingUid, installerUid);
14241
14242        final OriginInfo origin;
14243        if (stagedDir != null) {
14244            origin = OriginInfo.fromStagedFile(stagedDir);
14245        } else {
14246            origin = OriginInfo.fromStagedContainer(stagedCid);
14247        }
14248
14249        final Message msg = mHandler.obtainMessage(INIT_COPY);
14250        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14251                sessionParams.installReason);
14252        final InstallParams params = new InstallParams(origin, null, observer,
14253                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14254                verificationInfo, user, sessionParams.abiOverride,
14255                sessionParams.grantedRuntimePermissions, certificates, installReason);
14256        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14257        msg.obj = params;
14258
14259        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14260                System.identityHashCode(msg.obj));
14261        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14262                System.identityHashCode(msg.obj));
14263
14264        mHandler.sendMessage(msg);
14265    }
14266
14267    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14268            int userId) {
14269        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14270        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14271
14272        // Send a session commit broadcast
14273        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14274        info.installReason = pkgSetting.getInstallReason(userId);
14275        info.appPackageName = packageName;
14276        sendSessionCommitBroadcast(info, userId);
14277    }
14278
14279    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14280        if (ArrayUtils.isEmpty(userIds)) {
14281            return;
14282        }
14283        Bundle extras = new Bundle(1);
14284        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14285        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14286
14287        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14288                packageName, extras, 0, null, null, userIds);
14289        if (isSystem) {
14290            mHandler.post(() -> {
14291                        for (int userId : userIds) {
14292                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14293                        }
14294                    }
14295            );
14296        }
14297    }
14298
14299    /**
14300     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14301     * automatically without needing an explicit launch.
14302     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14303     */
14304    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14305        // If user is not running, the app didn't miss any broadcast
14306        if (!mUserManagerInternal.isUserRunning(userId)) {
14307            return;
14308        }
14309        final IActivityManager am = ActivityManager.getService();
14310        try {
14311            // Deliver LOCKED_BOOT_COMPLETED first
14312            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14313                    .setPackage(packageName);
14314            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14315            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14316                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14317
14318            // Deliver BOOT_COMPLETED only if user is unlocked
14319            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14320                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14321                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14322                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14323            }
14324        } catch (RemoteException e) {
14325            throw e.rethrowFromSystemServer();
14326        }
14327    }
14328
14329    @Override
14330    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14331            int userId) {
14332        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14333        PackageSetting pkgSetting;
14334        final int uid = Binder.getCallingUid();
14335        enforceCrossUserPermission(uid, userId,
14336                true /* requireFullPermission */, true /* checkShell */,
14337                "setApplicationHiddenSetting for user " + userId);
14338
14339        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14340            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14341            return false;
14342        }
14343
14344        long callingId = Binder.clearCallingIdentity();
14345        try {
14346            boolean sendAdded = false;
14347            boolean sendRemoved = false;
14348            // writer
14349            synchronized (mPackages) {
14350                pkgSetting = mSettings.mPackages.get(packageName);
14351                if (pkgSetting == null) {
14352                    return false;
14353                }
14354                // Do not allow "android" is being disabled
14355                if ("android".equals(packageName)) {
14356                    Slog.w(TAG, "Cannot hide package: android");
14357                    return false;
14358                }
14359                // Cannot hide static shared libs as they are considered
14360                // a part of the using app (emulating static linking). Also
14361                // static libs are installed always on internal storage.
14362                PackageParser.Package pkg = mPackages.get(packageName);
14363                if (pkg != null && pkg.staticSharedLibName != null) {
14364                    Slog.w(TAG, "Cannot hide package: " + packageName
14365                            + " providing static shared library: "
14366                            + pkg.staticSharedLibName);
14367                    return false;
14368                }
14369                // Only allow protected packages to hide themselves.
14370                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
14371                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14372                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14373                    return false;
14374                }
14375
14376                if (pkgSetting.getHidden(userId) != hidden) {
14377                    pkgSetting.setHidden(hidden, userId);
14378                    mSettings.writePackageRestrictionsLPr(userId);
14379                    if (hidden) {
14380                        sendRemoved = true;
14381                    } else {
14382                        sendAdded = true;
14383                    }
14384                }
14385            }
14386            if (sendAdded) {
14387                sendPackageAddedForUser(packageName, pkgSetting, userId);
14388                return true;
14389            }
14390            if (sendRemoved) {
14391                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14392                        "hiding pkg");
14393                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14394                return true;
14395            }
14396        } finally {
14397            Binder.restoreCallingIdentity(callingId);
14398        }
14399        return false;
14400    }
14401
14402    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14403            int userId) {
14404        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14405        info.removedPackage = packageName;
14406        info.installerPackageName = pkgSetting.installerPackageName;
14407        info.removedUsers = new int[] {userId};
14408        info.broadcastUsers = new int[] {userId};
14409        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14410        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14411    }
14412
14413    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14414        if (pkgList.length > 0) {
14415            Bundle extras = new Bundle(1);
14416            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14417
14418            sendPackageBroadcast(
14419                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14420                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14421                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14422                    new int[] {userId});
14423        }
14424    }
14425
14426    /**
14427     * Returns true if application is not found or there was an error. Otherwise it returns
14428     * the hidden state of the package for the given user.
14429     */
14430    @Override
14431    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14432        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14433        final int callingUid = Binder.getCallingUid();
14434        enforceCrossUserPermission(callingUid, userId,
14435                true /* requireFullPermission */, false /* checkShell */,
14436                "getApplicationHidden for user " + userId);
14437        PackageSetting ps;
14438        long callingId = Binder.clearCallingIdentity();
14439        try {
14440            // writer
14441            synchronized (mPackages) {
14442                ps = mSettings.mPackages.get(packageName);
14443                if (ps == null) {
14444                    return true;
14445                }
14446                if (filterAppAccessLPr(ps, callingUid, userId)) {
14447                    return true;
14448                }
14449                return ps.getHidden(userId);
14450            }
14451        } finally {
14452            Binder.restoreCallingIdentity(callingId);
14453        }
14454    }
14455
14456    /**
14457     * @hide
14458     */
14459    @Override
14460    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14461            int installReason) {
14462        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14463                null);
14464        PackageSetting pkgSetting;
14465        final int callingUid = Binder.getCallingUid();
14466        enforceCrossUserPermission(callingUid, userId,
14467                true /* requireFullPermission */, true /* checkShell */,
14468                "installExistingPackage for user " + userId);
14469        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14470            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14471        }
14472
14473        long callingId = Binder.clearCallingIdentity();
14474        try {
14475            boolean installed = false;
14476            final boolean instantApp =
14477                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14478            final boolean fullApp =
14479                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14480
14481            // writer
14482            synchronized (mPackages) {
14483                pkgSetting = mSettings.mPackages.get(packageName);
14484                if (pkgSetting == null) {
14485                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14486                }
14487                if (!pkgSetting.getInstalled(userId)) {
14488                    pkgSetting.setInstalled(true, userId);
14489                    pkgSetting.setHidden(false, userId);
14490                    pkgSetting.setInstallReason(installReason, userId);
14491                    mSettings.writePackageRestrictionsLPr(userId);
14492                    mSettings.writeKernelMappingLPr(pkgSetting);
14493                    installed = true;
14494                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14495                    // upgrade app from instant to full; we don't allow app downgrade
14496                    installed = true;
14497                }
14498                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14499            }
14500
14501            if (installed) {
14502                if (pkgSetting.pkg != null) {
14503                    synchronized (mInstallLock) {
14504                        // We don't need to freeze for a brand new install
14505                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14506                    }
14507                }
14508                sendPackageAddedForUser(packageName, pkgSetting, userId);
14509                synchronized (mPackages) {
14510                    updateSequenceNumberLP(packageName, new int[]{ userId });
14511                }
14512            }
14513        } finally {
14514            Binder.restoreCallingIdentity(callingId);
14515        }
14516
14517        return PackageManager.INSTALL_SUCCEEDED;
14518    }
14519
14520    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14521            boolean instantApp, boolean fullApp) {
14522        // no state specified; do nothing
14523        if (!instantApp && !fullApp) {
14524            return;
14525        }
14526        if (userId != UserHandle.USER_ALL) {
14527            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14528                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14529            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14530                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14531            }
14532        } else {
14533            for (int currentUserId : sUserManager.getUserIds()) {
14534                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14535                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14536                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14537                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14538                }
14539            }
14540        }
14541    }
14542
14543    boolean isUserRestricted(int userId, String restrictionKey) {
14544        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14545        if (restrictions.getBoolean(restrictionKey, false)) {
14546            Log.w(TAG, "User is restricted: " + restrictionKey);
14547            return true;
14548        }
14549        return false;
14550    }
14551
14552    @Override
14553    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14554            int userId) {
14555        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14556        enforceCrossUserPermission(Binder.getCallingUid(), userId,
14557                true /* requireFullPermission */, true /* checkShell */,
14558                "setPackagesSuspended for user " + userId);
14559
14560        if (ArrayUtils.isEmpty(packageNames)) {
14561            return packageNames;
14562        }
14563
14564        // List of package names for whom the suspended state has changed.
14565        List<String> changedPackages = new ArrayList<>(packageNames.length);
14566        // List of package names for whom the suspended state is not set as requested in this
14567        // method.
14568        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14569        long callingId = Binder.clearCallingIdentity();
14570        try {
14571            for (int i = 0; i < packageNames.length; i++) {
14572                String packageName = packageNames[i];
14573                boolean changed = false;
14574                final int appId;
14575                synchronized (mPackages) {
14576                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14577                    if (pkgSetting == null) {
14578                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14579                                + "\". Skipping suspending/un-suspending.");
14580                        unactionedPackages.add(packageName);
14581                        continue;
14582                    }
14583                    appId = pkgSetting.appId;
14584                    if (pkgSetting.getSuspended(userId) != suspended) {
14585                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14586                            unactionedPackages.add(packageName);
14587                            continue;
14588                        }
14589                        pkgSetting.setSuspended(suspended, userId);
14590                        mSettings.writePackageRestrictionsLPr(userId);
14591                        changed = true;
14592                        changedPackages.add(packageName);
14593                    }
14594                }
14595
14596                if (changed && suspended) {
14597                    killApplication(packageName, UserHandle.getUid(userId, appId),
14598                            "suspending package");
14599                }
14600            }
14601        } finally {
14602            Binder.restoreCallingIdentity(callingId);
14603        }
14604
14605        if (!changedPackages.isEmpty()) {
14606            sendPackagesSuspendedForUser(changedPackages.toArray(
14607                    new String[changedPackages.size()]), userId, suspended);
14608        }
14609
14610        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14611    }
14612
14613    @Override
14614    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14615        final int callingUid = Binder.getCallingUid();
14616        enforceCrossUserPermission(callingUid, userId,
14617                true /* requireFullPermission */, false /* checkShell */,
14618                "isPackageSuspendedForUser for user " + userId);
14619        synchronized (mPackages) {
14620            final PackageSetting ps = mSettings.mPackages.get(packageName);
14621            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14622                throw new IllegalArgumentException("Unknown target package: " + packageName);
14623            }
14624            return ps.getSuspended(userId);
14625        }
14626    }
14627
14628    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14629        if (isPackageDeviceAdmin(packageName, userId)) {
14630            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14631                    + "\": has an active device admin");
14632            return false;
14633        }
14634
14635        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14636        if (packageName.equals(activeLauncherPackageName)) {
14637            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14638                    + "\": contains the active launcher");
14639            return false;
14640        }
14641
14642        if (packageName.equals(mRequiredInstallerPackage)) {
14643            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14644                    + "\": required for package installation");
14645            return false;
14646        }
14647
14648        if (packageName.equals(mRequiredUninstallerPackage)) {
14649            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14650                    + "\": required for package uninstallation");
14651            return false;
14652        }
14653
14654        if (packageName.equals(mRequiredVerifierPackage)) {
14655            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14656                    + "\": required for package verification");
14657            return false;
14658        }
14659
14660        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14661            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14662                    + "\": is the default dialer");
14663            return false;
14664        }
14665
14666        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14667            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14668                    + "\": protected package");
14669            return false;
14670        }
14671
14672        // Cannot suspend static shared libs as they are considered
14673        // a part of the using app (emulating static linking). Also
14674        // static libs are installed always on internal storage.
14675        PackageParser.Package pkg = mPackages.get(packageName);
14676        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14677            Slog.w(TAG, "Cannot suspend package: " + packageName
14678                    + " providing static shared library: "
14679                    + pkg.staticSharedLibName);
14680            return false;
14681        }
14682
14683        return true;
14684    }
14685
14686    private String getActiveLauncherPackageName(int userId) {
14687        Intent intent = new Intent(Intent.ACTION_MAIN);
14688        intent.addCategory(Intent.CATEGORY_HOME);
14689        ResolveInfo resolveInfo = resolveIntent(
14690                intent,
14691                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14692                PackageManager.MATCH_DEFAULT_ONLY,
14693                userId);
14694
14695        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14696    }
14697
14698    private String getDefaultDialerPackageName(int userId) {
14699        synchronized (mPackages) {
14700            return mSettings.getDefaultDialerPackageNameLPw(userId);
14701        }
14702    }
14703
14704    @Override
14705    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14706        mContext.enforceCallingOrSelfPermission(
14707                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14708                "Only package verification agents can verify applications");
14709
14710        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14711        final PackageVerificationResponse response = new PackageVerificationResponse(
14712                verificationCode, Binder.getCallingUid());
14713        msg.arg1 = id;
14714        msg.obj = response;
14715        mHandler.sendMessage(msg);
14716    }
14717
14718    @Override
14719    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14720            long millisecondsToDelay) {
14721        mContext.enforceCallingOrSelfPermission(
14722                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14723                "Only package verification agents can extend verification timeouts");
14724
14725        final PackageVerificationState state = mPendingVerification.get(id);
14726        final PackageVerificationResponse response = new PackageVerificationResponse(
14727                verificationCodeAtTimeout, Binder.getCallingUid());
14728
14729        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14730            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14731        }
14732        if (millisecondsToDelay < 0) {
14733            millisecondsToDelay = 0;
14734        }
14735        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14736                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14737            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14738        }
14739
14740        if ((state != null) && !state.timeoutExtended()) {
14741            state.extendTimeout();
14742
14743            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14744            msg.arg1 = id;
14745            msg.obj = response;
14746            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14747        }
14748    }
14749
14750    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14751            int verificationCode, UserHandle user) {
14752        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14753        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14754        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14755        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14756        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14757
14758        mContext.sendBroadcastAsUser(intent, user,
14759                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14760    }
14761
14762    private ComponentName matchComponentForVerifier(String packageName,
14763            List<ResolveInfo> receivers) {
14764        ActivityInfo targetReceiver = null;
14765
14766        final int NR = receivers.size();
14767        for (int i = 0; i < NR; i++) {
14768            final ResolveInfo info = receivers.get(i);
14769            if (info.activityInfo == null) {
14770                continue;
14771            }
14772
14773            if (packageName.equals(info.activityInfo.packageName)) {
14774                targetReceiver = info.activityInfo;
14775                break;
14776            }
14777        }
14778
14779        if (targetReceiver == null) {
14780            return null;
14781        }
14782
14783        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14784    }
14785
14786    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14787            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14788        if (pkgInfo.verifiers.length == 0) {
14789            return null;
14790        }
14791
14792        final int N = pkgInfo.verifiers.length;
14793        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14794        for (int i = 0; i < N; i++) {
14795            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14796
14797            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14798                    receivers);
14799            if (comp == null) {
14800                continue;
14801            }
14802
14803            final int verifierUid = getUidForVerifier(verifierInfo);
14804            if (verifierUid == -1) {
14805                continue;
14806            }
14807
14808            if (DEBUG_VERIFY) {
14809                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14810                        + " with the correct signature");
14811            }
14812            sufficientVerifiers.add(comp);
14813            verificationState.addSufficientVerifier(verifierUid);
14814        }
14815
14816        return sufficientVerifiers;
14817    }
14818
14819    private int getUidForVerifier(VerifierInfo verifierInfo) {
14820        synchronized (mPackages) {
14821            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14822            if (pkg == null) {
14823                return -1;
14824            } else if (pkg.mSignatures.length != 1) {
14825                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14826                        + " has more than one signature; ignoring");
14827                return -1;
14828            }
14829
14830            /*
14831             * If the public key of the package's signature does not match
14832             * our expected public key, then this is a different package and
14833             * we should skip.
14834             */
14835
14836            final byte[] expectedPublicKey;
14837            try {
14838                final Signature verifierSig = pkg.mSignatures[0];
14839                final PublicKey publicKey = verifierSig.getPublicKey();
14840                expectedPublicKey = publicKey.getEncoded();
14841            } catch (CertificateException e) {
14842                return -1;
14843            }
14844
14845            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14846
14847            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14848                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14849                        + " does not have the expected public key; ignoring");
14850                return -1;
14851            }
14852
14853            return pkg.applicationInfo.uid;
14854        }
14855    }
14856
14857    @Override
14858    public void finishPackageInstall(int token, boolean didLaunch) {
14859        enforceSystemOrRoot("Only the system is allowed to finish installs");
14860
14861        if (DEBUG_INSTALL) {
14862            Slog.v(TAG, "BM finishing package install for " + token);
14863        }
14864        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14865
14866        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14867        mHandler.sendMessage(msg);
14868    }
14869
14870    /**
14871     * Get the verification agent timeout.  Used for both the APK verifier and the
14872     * intent filter verifier.
14873     *
14874     * @return verification timeout in milliseconds
14875     */
14876    private long getVerificationTimeout() {
14877        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14878                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14879                DEFAULT_VERIFICATION_TIMEOUT);
14880    }
14881
14882    /**
14883     * Get the default verification agent response code.
14884     *
14885     * @return default verification response code
14886     */
14887    private int getDefaultVerificationResponse(UserHandle user) {
14888        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14889            return PackageManager.VERIFICATION_REJECT;
14890        }
14891        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14892                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14893                DEFAULT_VERIFICATION_RESPONSE);
14894    }
14895
14896    /**
14897     * Check whether or not package verification has been enabled.
14898     *
14899     * @return true if verification should be performed
14900     */
14901    private boolean isVerificationEnabled(int userId, int installFlags) {
14902        if (!DEFAULT_VERIFY_ENABLE) {
14903            return false;
14904        }
14905
14906        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14907
14908        // Check if installing from ADB
14909        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14910            // Do not run verification in a test harness environment
14911            if (ActivityManager.isRunningInTestHarness()) {
14912                return false;
14913            }
14914            if (ensureVerifyAppsEnabled) {
14915                return true;
14916            }
14917            // Check if the developer does not want package verification for ADB installs
14918            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14919                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14920                return false;
14921            }
14922        }
14923
14924        if (ensureVerifyAppsEnabled) {
14925            return true;
14926        }
14927
14928        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14929                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14930    }
14931
14932    @Override
14933    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14934            throws RemoteException {
14935        mContext.enforceCallingOrSelfPermission(
14936                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14937                "Only intentfilter verification agents can verify applications");
14938
14939        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14940        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14941                Binder.getCallingUid(), verificationCode, failedDomains);
14942        msg.arg1 = id;
14943        msg.obj = response;
14944        mHandler.sendMessage(msg);
14945    }
14946
14947    @Override
14948    public int getIntentVerificationStatus(String packageName, int userId) {
14949        final int callingUid = Binder.getCallingUid();
14950        if (getInstantAppPackageName(callingUid) != null) {
14951            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14952        }
14953        synchronized (mPackages) {
14954            final PackageSetting ps = mSettings.mPackages.get(packageName);
14955            if (ps == null
14956                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14957                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14958            }
14959            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14960        }
14961    }
14962
14963    @Override
14964    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14965        mContext.enforceCallingOrSelfPermission(
14966                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14967
14968        boolean result = false;
14969        synchronized (mPackages) {
14970            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14971        }
14972        if (result) {
14973            scheduleWritePackageRestrictionsLocked(userId);
14974        }
14975        return result;
14976    }
14977
14978    @Override
14979    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14980            String packageName) {
14981        final int callingUid = Binder.getCallingUid();
14982        if (getInstantAppPackageName(callingUid) != null) {
14983            return ParceledListSlice.emptyList();
14984        }
14985        synchronized (mPackages) {
14986            final PackageSetting ps = mSettings.mPackages.get(packageName);
14987            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14988                return ParceledListSlice.emptyList();
14989            }
14990            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14991        }
14992    }
14993
14994    @Override
14995    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14996        if (TextUtils.isEmpty(packageName)) {
14997            return ParceledListSlice.emptyList();
14998        }
14999        final int callingUid = Binder.getCallingUid();
15000        final int callingUserId = UserHandle.getUserId(callingUid);
15001        synchronized (mPackages) {
15002            PackageParser.Package pkg = mPackages.get(packageName);
15003            if (pkg == null || pkg.activities == null) {
15004                return ParceledListSlice.emptyList();
15005            }
15006            if (pkg.mExtras == null) {
15007                return ParceledListSlice.emptyList();
15008            }
15009            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15010            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15011                return ParceledListSlice.emptyList();
15012            }
15013            final int count = pkg.activities.size();
15014            ArrayList<IntentFilter> result = new ArrayList<>();
15015            for (int n=0; n<count; n++) {
15016                PackageParser.Activity activity = pkg.activities.get(n);
15017                if (activity.intents != null && activity.intents.size() > 0) {
15018                    result.addAll(activity.intents);
15019                }
15020            }
15021            return new ParceledListSlice<>(result);
15022        }
15023    }
15024
15025    @Override
15026    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15027        mContext.enforceCallingOrSelfPermission(
15028                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15029
15030        synchronized (mPackages) {
15031            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15032            if (packageName != null) {
15033                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15034                        packageName, userId);
15035            }
15036            return result;
15037        }
15038    }
15039
15040    @Override
15041    public String getDefaultBrowserPackageName(int userId) {
15042        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15043            return null;
15044        }
15045        synchronized (mPackages) {
15046            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15047        }
15048    }
15049
15050    /**
15051     * Get the "allow unknown sources" setting.
15052     *
15053     * @return the current "allow unknown sources" setting
15054     */
15055    private int getUnknownSourcesSettings() {
15056        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15057                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15058                -1);
15059    }
15060
15061    @Override
15062    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15063        final int callingUid = Binder.getCallingUid();
15064        if (getInstantAppPackageName(callingUid) != null) {
15065            return;
15066        }
15067        // writer
15068        synchronized (mPackages) {
15069            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15070            if (targetPackageSetting == null) {
15071                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15072            }
15073
15074            PackageSetting installerPackageSetting;
15075            if (installerPackageName != null) {
15076                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15077                if (installerPackageSetting == null) {
15078                    throw new IllegalArgumentException("Unknown installer package: "
15079                            + installerPackageName);
15080                }
15081            } else {
15082                installerPackageSetting = null;
15083            }
15084
15085            Signature[] callerSignature;
15086            Object obj = mSettings.getUserIdLPr(callingUid);
15087            if (obj != null) {
15088                if (obj instanceof SharedUserSetting) {
15089                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15090                } else if (obj instanceof PackageSetting) {
15091                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15092                } else {
15093                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15094                }
15095            } else {
15096                throw new SecurityException("Unknown calling UID: " + callingUid);
15097            }
15098
15099            // Verify: can't set installerPackageName to a package that is
15100            // not signed with the same cert as the caller.
15101            if (installerPackageSetting != null) {
15102                if (compareSignatures(callerSignature,
15103                        installerPackageSetting.signatures.mSignatures)
15104                        != PackageManager.SIGNATURE_MATCH) {
15105                    throw new SecurityException(
15106                            "Caller does not have same cert as new installer package "
15107                            + installerPackageName);
15108                }
15109            }
15110
15111            // Verify: if target already has an installer package, it must
15112            // be signed with the same cert as the caller.
15113            if (targetPackageSetting.installerPackageName != null) {
15114                PackageSetting setting = mSettings.mPackages.get(
15115                        targetPackageSetting.installerPackageName);
15116                // If the currently set package isn't valid, then it's always
15117                // okay to change it.
15118                if (setting != null) {
15119                    if (compareSignatures(callerSignature,
15120                            setting.signatures.mSignatures)
15121                            != PackageManager.SIGNATURE_MATCH) {
15122                        throw new SecurityException(
15123                                "Caller does not have same cert as old installer package "
15124                                + targetPackageSetting.installerPackageName);
15125                    }
15126                }
15127            }
15128
15129            // Okay!
15130            targetPackageSetting.installerPackageName = installerPackageName;
15131            if (installerPackageName != null) {
15132                mSettings.mInstallerPackages.add(installerPackageName);
15133            }
15134            scheduleWriteSettingsLocked();
15135        }
15136    }
15137
15138    @Override
15139    public void setApplicationCategoryHint(String packageName, int categoryHint,
15140            String callerPackageName) {
15141        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15142            throw new SecurityException("Instant applications don't have access to this method");
15143        }
15144        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15145                callerPackageName);
15146        synchronized (mPackages) {
15147            PackageSetting ps = mSettings.mPackages.get(packageName);
15148            if (ps == null) {
15149                throw new IllegalArgumentException("Unknown target package " + packageName);
15150            }
15151
15152            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15153                throw new IllegalArgumentException("Calling package " + callerPackageName
15154                        + " is not installer for " + packageName);
15155            }
15156
15157            if (ps.categoryHint != categoryHint) {
15158                ps.categoryHint = categoryHint;
15159                scheduleWriteSettingsLocked();
15160            }
15161        }
15162    }
15163
15164    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15165        // Queue up an async operation since the package installation may take a little while.
15166        mHandler.post(new Runnable() {
15167            public void run() {
15168                mHandler.removeCallbacks(this);
15169                 // Result object to be returned
15170                PackageInstalledInfo res = new PackageInstalledInfo();
15171                res.setReturnCode(currentStatus);
15172                res.uid = -1;
15173                res.pkg = null;
15174                res.removedInfo = null;
15175                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15176                    args.doPreInstall(res.returnCode);
15177                    synchronized (mInstallLock) {
15178                        installPackageTracedLI(args, res);
15179                    }
15180                    args.doPostInstall(res.returnCode, res.uid);
15181                }
15182
15183                // A restore should be performed at this point if (a) the install
15184                // succeeded, (b) the operation is not an update, and (c) the new
15185                // package has not opted out of backup participation.
15186                final boolean update = res.removedInfo != null
15187                        && res.removedInfo.removedPackage != null;
15188                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15189                boolean doRestore = !update
15190                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15191
15192                // Set up the post-install work request bookkeeping.  This will be used
15193                // and cleaned up by the post-install event handling regardless of whether
15194                // there's a restore pass performed.  Token values are >= 1.
15195                int token;
15196                if (mNextInstallToken < 0) mNextInstallToken = 1;
15197                token = mNextInstallToken++;
15198
15199                PostInstallData data = new PostInstallData(args, res);
15200                mRunningInstalls.put(token, data);
15201                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15202
15203                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15204                    // Pass responsibility to the Backup Manager.  It will perform a
15205                    // restore if appropriate, then pass responsibility back to the
15206                    // Package Manager to run the post-install observer callbacks
15207                    // and broadcasts.
15208                    IBackupManager bm = IBackupManager.Stub.asInterface(
15209                            ServiceManager.getService(Context.BACKUP_SERVICE));
15210                    if (bm != null) {
15211                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15212                                + " to BM for possible restore");
15213                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15214                        try {
15215                            // TODO: http://b/22388012
15216                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15217                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15218                            } else {
15219                                doRestore = false;
15220                            }
15221                        } catch (RemoteException e) {
15222                            // can't happen; the backup manager is local
15223                        } catch (Exception e) {
15224                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15225                            doRestore = false;
15226                        }
15227                    } else {
15228                        Slog.e(TAG, "Backup Manager not found!");
15229                        doRestore = false;
15230                    }
15231                }
15232
15233                if (!doRestore) {
15234                    // No restore possible, or the Backup Manager was mysteriously not
15235                    // available -- just fire the post-install work request directly.
15236                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15237
15238                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15239
15240                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15241                    mHandler.sendMessage(msg);
15242                }
15243            }
15244        });
15245    }
15246
15247    /**
15248     * Callback from PackageSettings whenever an app is first transitioned out of the
15249     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15250     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15251     * here whether the app is the target of an ongoing install, and only send the
15252     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15253     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15254     * handling.
15255     */
15256    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15257        // Serialize this with the rest of the install-process message chain.  In the
15258        // restore-at-install case, this Runnable will necessarily run before the
15259        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15260        // are coherent.  In the non-restore case, the app has already completed install
15261        // and been launched through some other means, so it is not in a problematic
15262        // state for observers to see the FIRST_LAUNCH signal.
15263        mHandler.post(new Runnable() {
15264            @Override
15265            public void run() {
15266                for (int i = 0; i < mRunningInstalls.size(); i++) {
15267                    final PostInstallData data = mRunningInstalls.valueAt(i);
15268                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15269                        continue;
15270                    }
15271                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15272                        // right package; but is it for the right user?
15273                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15274                            if (userId == data.res.newUsers[uIndex]) {
15275                                if (DEBUG_BACKUP) {
15276                                    Slog.i(TAG, "Package " + pkgName
15277                                            + " being restored so deferring FIRST_LAUNCH");
15278                                }
15279                                return;
15280                            }
15281                        }
15282                    }
15283                }
15284                // didn't find it, so not being restored
15285                if (DEBUG_BACKUP) {
15286                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15287                }
15288                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15289            }
15290        });
15291    }
15292
15293    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15294        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15295                installerPkg, null, userIds);
15296    }
15297
15298    private abstract class HandlerParams {
15299        private static final int MAX_RETRIES = 4;
15300
15301        /**
15302         * Number of times startCopy() has been attempted and had a non-fatal
15303         * error.
15304         */
15305        private int mRetries = 0;
15306
15307        /** User handle for the user requesting the information or installation. */
15308        private final UserHandle mUser;
15309        String traceMethod;
15310        int traceCookie;
15311
15312        HandlerParams(UserHandle user) {
15313            mUser = user;
15314        }
15315
15316        UserHandle getUser() {
15317            return mUser;
15318        }
15319
15320        HandlerParams setTraceMethod(String traceMethod) {
15321            this.traceMethod = traceMethod;
15322            return this;
15323        }
15324
15325        HandlerParams setTraceCookie(int traceCookie) {
15326            this.traceCookie = traceCookie;
15327            return this;
15328        }
15329
15330        final boolean startCopy() {
15331            boolean res;
15332            try {
15333                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15334
15335                if (++mRetries > MAX_RETRIES) {
15336                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15337                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15338                    handleServiceError();
15339                    return false;
15340                } else {
15341                    handleStartCopy();
15342                    res = true;
15343                }
15344            } catch (RemoteException e) {
15345                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15346                mHandler.sendEmptyMessage(MCS_RECONNECT);
15347                res = false;
15348            }
15349            handleReturnCode();
15350            return res;
15351        }
15352
15353        final void serviceError() {
15354            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15355            handleServiceError();
15356            handleReturnCode();
15357        }
15358
15359        abstract void handleStartCopy() throws RemoteException;
15360        abstract void handleServiceError();
15361        abstract void handleReturnCode();
15362    }
15363
15364    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15365        for (File path : paths) {
15366            try {
15367                mcs.clearDirectory(path.getAbsolutePath());
15368            } catch (RemoteException e) {
15369            }
15370        }
15371    }
15372
15373    static class OriginInfo {
15374        /**
15375         * Location where install is coming from, before it has been
15376         * copied/renamed into place. This could be a single monolithic APK
15377         * file, or a cluster directory. This location may be untrusted.
15378         */
15379        final File file;
15380        final String cid;
15381
15382        /**
15383         * Flag indicating that {@link #file} or {@link #cid} has already been
15384         * staged, meaning downstream users don't need to defensively copy the
15385         * contents.
15386         */
15387        final boolean staged;
15388
15389        /**
15390         * Flag indicating that {@link #file} or {@link #cid} is an already
15391         * installed app that is being moved.
15392         */
15393        final boolean existing;
15394
15395        final String resolvedPath;
15396        final File resolvedFile;
15397
15398        static OriginInfo fromNothing() {
15399            return new OriginInfo(null, null, false, false);
15400        }
15401
15402        static OriginInfo fromUntrustedFile(File file) {
15403            return new OriginInfo(file, null, false, false);
15404        }
15405
15406        static OriginInfo fromExistingFile(File file) {
15407            return new OriginInfo(file, null, false, true);
15408        }
15409
15410        static OriginInfo fromStagedFile(File file) {
15411            return new OriginInfo(file, null, true, false);
15412        }
15413
15414        static OriginInfo fromStagedContainer(String cid) {
15415            return new OriginInfo(null, cid, true, false);
15416        }
15417
15418        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15419            this.file = file;
15420            this.cid = cid;
15421            this.staged = staged;
15422            this.existing = existing;
15423
15424            if (cid != null) {
15425                resolvedPath = PackageHelper.getSdDir(cid);
15426                resolvedFile = new File(resolvedPath);
15427            } else if (file != null) {
15428                resolvedPath = file.getAbsolutePath();
15429                resolvedFile = file;
15430            } else {
15431                resolvedPath = null;
15432                resolvedFile = null;
15433            }
15434        }
15435    }
15436
15437    static class MoveInfo {
15438        final int moveId;
15439        final String fromUuid;
15440        final String toUuid;
15441        final String packageName;
15442        final String dataAppName;
15443        final int appId;
15444        final String seinfo;
15445        final int targetSdkVersion;
15446
15447        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15448                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15449            this.moveId = moveId;
15450            this.fromUuid = fromUuid;
15451            this.toUuid = toUuid;
15452            this.packageName = packageName;
15453            this.dataAppName = dataAppName;
15454            this.appId = appId;
15455            this.seinfo = seinfo;
15456            this.targetSdkVersion = targetSdkVersion;
15457        }
15458    }
15459
15460    static class VerificationInfo {
15461        /** A constant used to indicate that a uid value is not present. */
15462        public static final int NO_UID = -1;
15463
15464        /** URI referencing where the package was downloaded from. */
15465        final Uri originatingUri;
15466
15467        /** HTTP referrer URI associated with the originatingURI. */
15468        final Uri referrer;
15469
15470        /** UID of the application that the install request originated from. */
15471        final int originatingUid;
15472
15473        /** UID of application requesting the install */
15474        final int installerUid;
15475
15476        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15477            this.originatingUri = originatingUri;
15478            this.referrer = referrer;
15479            this.originatingUid = originatingUid;
15480            this.installerUid = installerUid;
15481        }
15482    }
15483
15484    class InstallParams extends HandlerParams {
15485        final OriginInfo origin;
15486        final MoveInfo move;
15487        final IPackageInstallObserver2 observer;
15488        int installFlags;
15489        final String installerPackageName;
15490        final String volumeUuid;
15491        private InstallArgs mArgs;
15492        private int mRet;
15493        final String packageAbiOverride;
15494        final String[] grantedRuntimePermissions;
15495        final VerificationInfo verificationInfo;
15496        final Certificate[][] certificates;
15497        final int installReason;
15498
15499        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15500                int installFlags, String installerPackageName, String volumeUuid,
15501                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15502                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15503            super(user);
15504            this.origin = origin;
15505            this.move = move;
15506            this.observer = observer;
15507            this.installFlags = installFlags;
15508            this.installerPackageName = installerPackageName;
15509            this.volumeUuid = volumeUuid;
15510            this.verificationInfo = verificationInfo;
15511            this.packageAbiOverride = packageAbiOverride;
15512            this.grantedRuntimePermissions = grantedPermissions;
15513            this.certificates = certificates;
15514            this.installReason = installReason;
15515        }
15516
15517        @Override
15518        public String toString() {
15519            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15520                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15521        }
15522
15523        private int installLocationPolicy(PackageInfoLite pkgLite) {
15524            String packageName = pkgLite.packageName;
15525            int installLocation = pkgLite.installLocation;
15526            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15527            // reader
15528            synchronized (mPackages) {
15529                // Currently installed package which the new package is attempting to replace or
15530                // null if no such package is installed.
15531                PackageParser.Package installedPkg = mPackages.get(packageName);
15532                // Package which currently owns the data which the new package will own if installed.
15533                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15534                // will be null whereas dataOwnerPkg will contain information about the package
15535                // which was uninstalled while keeping its data.
15536                PackageParser.Package dataOwnerPkg = installedPkg;
15537                if (dataOwnerPkg  == null) {
15538                    PackageSetting ps = mSettings.mPackages.get(packageName);
15539                    if (ps != null) {
15540                        dataOwnerPkg = ps.pkg;
15541                    }
15542                }
15543
15544                if (dataOwnerPkg != null) {
15545                    // If installed, the package will get access to data left on the device by its
15546                    // predecessor. As a security measure, this is permited only if this is not a
15547                    // version downgrade or if the predecessor package is marked as debuggable and
15548                    // a downgrade is explicitly requested.
15549                    //
15550                    // On debuggable platform builds, downgrades are permitted even for
15551                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15552                    // not offer security guarantees and thus it's OK to disable some security
15553                    // mechanisms to make debugging/testing easier on those builds. However, even on
15554                    // debuggable builds downgrades of packages are permitted only if requested via
15555                    // installFlags. This is because we aim to keep the behavior of debuggable
15556                    // platform builds as close as possible to the behavior of non-debuggable
15557                    // platform builds.
15558                    final boolean downgradeRequested =
15559                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15560                    final boolean packageDebuggable =
15561                                (dataOwnerPkg.applicationInfo.flags
15562                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15563                    final boolean downgradePermitted =
15564                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15565                    if (!downgradePermitted) {
15566                        try {
15567                            checkDowngrade(dataOwnerPkg, pkgLite);
15568                        } catch (PackageManagerException e) {
15569                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15570                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15571                        }
15572                    }
15573                }
15574
15575                if (installedPkg != null) {
15576                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15577                        // Check for updated system application.
15578                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15579                            if (onSd) {
15580                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15581                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15582                            }
15583                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15584                        } else {
15585                            if (onSd) {
15586                                // Install flag overrides everything.
15587                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15588                            }
15589                            // If current upgrade specifies particular preference
15590                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15591                                // Application explicitly specified internal.
15592                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15593                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15594                                // App explictly prefers external. Let policy decide
15595                            } else {
15596                                // Prefer previous location
15597                                if (isExternal(installedPkg)) {
15598                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15599                                }
15600                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15601                            }
15602                        }
15603                    } else {
15604                        // Invalid install. Return error code
15605                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15606                    }
15607                }
15608            }
15609            // All the special cases have been taken care of.
15610            // Return result based on recommended install location.
15611            if (onSd) {
15612                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15613            }
15614            return pkgLite.recommendedInstallLocation;
15615        }
15616
15617        /*
15618         * Invoke remote method to get package information and install
15619         * location values. Override install location based on default
15620         * policy if needed and then create install arguments based
15621         * on the install location.
15622         */
15623        public void handleStartCopy() throws RemoteException {
15624            int ret = PackageManager.INSTALL_SUCCEEDED;
15625
15626            // If we're already staged, we've firmly committed to an install location
15627            if (origin.staged) {
15628                if (origin.file != null) {
15629                    installFlags |= PackageManager.INSTALL_INTERNAL;
15630                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15631                } else if (origin.cid != null) {
15632                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15633                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15634                } else {
15635                    throw new IllegalStateException("Invalid stage location");
15636                }
15637            }
15638
15639            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15640            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15641            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15642            PackageInfoLite pkgLite = null;
15643
15644            if (onInt && onSd) {
15645                // Check if both bits are set.
15646                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15647                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15648            } else if (onSd && ephemeral) {
15649                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15650                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15651            } else {
15652                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15653                        packageAbiOverride);
15654
15655                if (DEBUG_EPHEMERAL && ephemeral) {
15656                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15657                }
15658
15659                /*
15660                 * If we have too little free space, try to free cache
15661                 * before giving up.
15662                 */
15663                if (!origin.staged && pkgLite.recommendedInstallLocation
15664                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15665                    // TODO: focus freeing disk space on the target device
15666                    final StorageManager storage = StorageManager.from(mContext);
15667                    final long lowThreshold = storage.getStorageLowBytes(
15668                            Environment.getDataDirectory());
15669
15670                    final long sizeBytes = mContainerService.calculateInstalledSize(
15671                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15672
15673                    try {
15674                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15675                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15676                                installFlags, packageAbiOverride);
15677                    } catch (InstallerException e) {
15678                        Slog.w(TAG, "Failed to free cache", e);
15679                    }
15680
15681                    /*
15682                     * The cache free must have deleted the file we
15683                     * downloaded to install.
15684                     *
15685                     * TODO: fix the "freeCache" call to not delete
15686                     *       the file we care about.
15687                     */
15688                    if (pkgLite.recommendedInstallLocation
15689                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15690                        pkgLite.recommendedInstallLocation
15691                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15692                    }
15693                }
15694            }
15695
15696            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15697                int loc = pkgLite.recommendedInstallLocation;
15698                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15699                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15700                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15701                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15702                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15703                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15704                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15705                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15706                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15707                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15708                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15709                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15710                } else {
15711                    // Override with defaults if needed.
15712                    loc = installLocationPolicy(pkgLite);
15713                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15714                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15715                    } else if (!onSd && !onInt) {
15716                        // Override install location with flags
15717                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15718                            // Set the flag to install on external media.
15719                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15720                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15721                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15722                            if (DEBUG_EPHEMERAL) {
15723                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15724                            }
15725                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15726                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15727                                    |PackageManager.INSTALL_INTERNAL);
15728                        } else {
15729                            // Make sure the flag for installing on external
15730                            // media is unset
15731                            installFlags |= PackageManager.INSTALL_INTERNAL;
15732                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15733                        }
15734                    }
15735                }
15736            }
15737
15738            final InstallArgs args = createInstallArgs(this);
15739            mArgs = args;
15740
15741            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15742                // TODO: http://b/22976637
15743                // Apps installed for "all" users use the device owner to verify the app
15744                UserHandle verifierUser = getUser();
15745                if (verifierUser == UserHandle.ALL) {
15746                    verifierUser = UserHandle.SYSTEM;
15747                }
15748
15749                /*
15750                 * Determine if we have any installed package verifiers. If we
15751                 * do, then we'll defer to them to verify the packages.
15752                 */
15753                final int requiredUid = mRequiredVerifierPackage == null ? -1
15754                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15755                                verifierUser.getIdentifier());
15756                if (!origin.existing && requiredUid != -1
15757                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15758                    final Intent verification = new Intent(
15759                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15760                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15761                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15762                            PACKAGE_MIME_TYPE);
15763                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15764
15765                    // Query all live verifiers based on current user state
15766                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15767                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15768
15769                    if (DEBUG_VERIFY) {
15770                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15771                                + verification.toString() + " with " + pkgLite.verifiers.length
15772                                + " optional verifiers");
15773                    }
15774
15775                    final int verificationId = mPendingVerificationToken++;
15776
15777                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15778
15779                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15780                            installerPackageName);
15781
15782                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15783                            installFlags);
15784
15785                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15786                            pkgLite.packageName);
15787
15788                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15789                            pkgLite.versionCode);
15790
15791                    if (verificationInfo != null) {
15792                        if (verificationInfo.originatingUri != null) {
15793                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15794                                    verificationInfo.originatingUri);
15795                        }
15796                        if (verificationInfo.referrer != null) {
15797                            verification.putExtra(Intent.EXTRA_REFERRER,
15798                                    verificationInfo.referrer);
15799                        }
15800                        if (verificationInfo.originatingUid >= 0) {
15801                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15802                                    verificationInfo.originatingUid);
15803                        }
15804                        if (verificationInfo.installerUid >= 0) {
15805                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15806                                    verificationInfo.installerUid);
15807                        }
15808                    }
15809
15810                    final PackageVerificationState verificationState = new PackageVerificationState(
15811                            requiredUid, args);
15812
15813                    mPendingVerification.append(verificationId, verificationState);
15814
15815                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15816                            receivers, verificationState);
15817
15818                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15819                    final long idleDuration = getVerificationTimeout();
15820
15821                    /*
15822                     * If any sufficient verifiers were listed in the package
15823                     * manifest, attempt to ask them.
15824                     */
15825                    if (sufficientVerifiers != null) {
15826                        final int N = sufficientVerifiers.size();
15827                        if (N == 0) {
15828                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15829                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15830                        } else {
15831                            for (int i = 0; i < N; i++) {
15832                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15833                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15834                                        verifierComponent.getPackageName(), idleDuration,
15835                                        verifierUser.getIdentifier(), false, "package verifier");
15836
15837                                final Intent sufficientIntent = new Intent(verification);
15838                                sufficientIntent.setComponent(verifierComponent);
15839                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15840                            }
15841                        }
15842                    }
15843
15844                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15845                            mRequiredVerifierPackage, receivers);
15846                    if (ret == PackageManager.INSTALL_SUCCEEDED
15847                            && mRequiredVerifierPackage != null) {
15848                        Trace.asyncTraceBegin(
15849                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15850                        /*
15851                         * Send the intent to the required verification agent,
15852                         * but only start the verification timeout after the
15853                         * target BroadcastReceivers have run.
15854                         */
15855                        verification.setComponent(requiredVerifierComponent);
15856                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15857                                mRequiredVerifierPackage, idleDuration,
15858                                verifierUser.getIdentifier(), false, "package verifier");
15859                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15860                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15861                                new BroadcastReceiver() {
15862                                    @Override
15863                                    public void onReceive(Context context, Intent intent) {
15864                                        final Message msg = mHandler
15865                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15866                                        msg.arg1 = verificationId;
15867                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15868                                    }
15869                                }, null, 0, null, null);
15870
15871                        /*
15872                         * We don't want the copy to proceed until verification
15873                         * succeeds, so null out this field.
15874                         */
15875                        mArgs = null;
15876                    }
15877                } else {
15878                    /*
15879                     * No package verification is enabled, so immediately start
15880                     * the remote call to initiate copy using temporary file.
15881                     */
15882                    ret = args.copyApk(mContainerService, true);
15883                }
15884            }
15885
15886            mRet = ret;
15887        }
15888
15889        @Override
15890        void handleReturnCode() {
15891            // If mArgs is null, then MCS couldn't be reached. When it
15892            // reconnects, it will try again to install. At that point, this
15893            // will succeed.
15894            if (mArgs != null) {
15895                processPendingInstall(mArgs, mRet);
15896            }
15897        }
15898
15899        @Override
15900        void handleServiceError() {
15901            mArgs = createInstallArgs(this);
15902            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15903        }
15904
15905        public boolean isForwardLocked() {
15906            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15907        }
15908    }
15909
15910    /**
15911     * Used during creation of InstallArgs
15912     *
15913     * @param installFlags package installation flags
15914     * @return true if should be installed on external storage
15915     */
15916    private static boolean installOnExternalAsec(int installFlags) {
15917        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15918            return false;
15919        }
15920        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15921            return true;
15922        }
15923        return false;
15924    }
15925
15926    /**
15927     * Used during creation of InstallArgs
15928     *
15929     * @param installFlags package installation flags
15930     * @return true if should be installed as forward locked
15931     */
15932    private static boolean installForwardLocked(int installFlags) {
15933        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15934    }
15935
15936    private InstallArgs createInstallArgs(InstallParams params) {
15937        if (params.move != null) {
15938            return new MoveInstallArgs(params);
15939        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15940            return new AsecInstallArgs(params);
15941        } else {
15942            return new FileInstallArgs(params);
15943        }
15944    }
15945
15946    /**
15947     * Create args that describe an existing installed package. Typically used
15948     * when cleaning up old installs, or used as a move source.
15949     */
15950    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15951            String resourcePath, String[] instructionSets) {
15952        final boolean isInAsec;
15953        if (installOnExternalAsec(installFlags)) {
15954            /* Apps on SD card are always in ASEC containers. */
15955            isInAsec = true;
15956        } else if (installForwardLocked(installFlags)
15957                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15958            /*
15959             * Forward-locked apps are only in ASEC containers if they're the
15960             * new style
15961             */
15962            isInAsec = true;
15963        } else {
15964            isInAsec = false;
15965        }
15966
15967        if (isInAsec) {
15968            return new AsecInstallArgs(codePath, instructionSets,
15969                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15970        } else {
15971            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15972        }
15973    }
15974
15975    static abstract class InstallArgs {
15976        /** @see InstallParams#origin */
15977        final OriginInfo origin;
15978        /** @see InstallParams#move */
15979        final MoveInfo move;
15980
15981        final IPackageInstallObserver2 observer;
15982        // Always refers to PackageManager flags only
15983        final int installFlags;
15984        final String installerPackageName;
15985        final String volumeUuid;
15986        final UserHandle user;
15987        final String abiOverride;
15988        final String[] installGrantPermissions;
15989        /** If non-null, drop an async trace when the install completes */
15990        final String traceMethod;
15991        final int traceCookie;
15992        final Certificate[][] certificates;
15993        final int installReason;
15994
15995        // The list of instruction sets supported by this app. This is currently
15996        // only used during the rmdex() phase to clean up resources. We can get rid of this
15997        // if we move dex files under the common app path.
15998        /* nullable */ String[] instructionSets;
15999
16000        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16001                int installFlags, String installerPackageName, String volumeUuid,
16002                UserHandle user, String[] instructionSets,
16003                String abiOverride, String[] installGrantPermissions,
16004                String traceMethod, int traceCookie, Certificate[][] certificates,
16005                int installReason) {
16006            this.origin = origin;
16007            this.move = move;
16008            this.installFlags = installFlags;
16009            this.observer = observer;
16010            this.installerPackageName = installerPackageName;
16011            this.volumeUuid = volumeUuid;
16012            this.user = user;
16013            this.instructionSets = instructionSets;
16014            this.abiOverride = abiOverride;
16015            this.installGrantPermissions = installGrantPermissions;
16016            this.traceMethod = traceMethod;
16017            this.traceCookie = traceCookie;
16018            this.certificates = certificates;
16019            this.installReason = installReason;
16020        }
16021
16022        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16023        abstract int doPreInstall(int status);
16024
16025        /**
16026         * Rename package into final resting place. All paths on the given
16027         * scanned package should be updated to reflect the rename.
16028         */
16029        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16030        abstract int doPostInstall(int status, int uid);
16031
16032        /** @see PackageSettingBase#codePathString */
16033        abstract String getCodePath();
16034        /** @see PackageSettingBase#resourcePathString */
16035        abstract String getResourcePath();
16036
16037        // Need installer lock especially for dex file removal.
16038        abstract void cleanUpResourcesLI();
16039        abstract boolean doPostDeleteLI(boolean delete);
16040
16041        /**
16042         * Called before the source arguments are copied. This is used mostly
16043         * for MoveParams when it needs to read the source file to put it in the
16044         * destination.
16045         */
16046        int doPreCopy() {
16047            return PackageManager.INSTALL_SUCCEEDED;
16048        }
16049
16050        /**
16051         * Called after the source arguments are copied. This is used mostly for
16052         * MoveParams when it needs to read the source file to put it in the
16053         * destination.
16054         */
16055        int doPostCopy(int uid) {
16056            return PackageManager.INSTALL_SUCCEEDED;
16057        }
16058
16059        protected boolean isFwdLocked() {
16060            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16061        }
16062
16063        protected boolean isExternalAsec() {
16064            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16065        }
16066
16067        protected boolean isEphemeral() {
16068            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16069        }
16070
16071        UserHandle getUser() {
16072            return user;
16073        }
16074    }
16075
16076    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16077        if (!allCodePaths.isEmpty()) {
16078            if (instructionSets == null) {
16079                throw new IllegalStateException("instructionSet == null");
16080            }
16081            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16082            for (String codePath : allCodePaths) {
16083                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16084                    try {
16085                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16086                    } catch (InstallerException ignored) {
16087                    }
16088                }
16089            }
16090        }
16091    }
16092
16093    /**
16094     * Logic to handle installation of non-ASEC applications, including copying
16095     * and renaming logic.
16096     */
16097    class FileInstallArgs extends InstallArgs {
16098        private File codeFile;
16099        private File resourceFile;
16100
16101        // Example topology:
16102        // /data/app/com.example/base.apk
16103        // /data/app/com.example/split_foo.apk
16104        // /data/app/com.example/lib/arm/libfoo.so
16105        // /data/app/com.example/lib/arm64/libfoo.so
16106        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16107
16108        /** New install */
16109        FileInstallArgs(InstallParams params) {
16110            super(params.origin, params.move, params.observer, params.installFlags,
16111                    params.installerPackageName, params.volumeUuid,
16112                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16113                    params.grantedRuntimePermissions,
16114                    params.traceMethod, params.traceCookie, params.certificates,
16115                    params.installReason);
16116            if (isFwdLocked()) {
16117                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16118            }
16119        }
16120
16121        /** Existing install */
16122        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16123            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16124                    null, null, null, 0, null /*certificates*/,
16125                    PackageManager.INSTALL_REASON_UNKNOWN);
16126            this.codeFile = (codePath != null) ? new File(codePath) : null;
16127            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16128        }
16129
16130        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16131            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16132            try {
16133                return doCopyApk(imcs, temp);
16134            } finally {
16135                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16136            }
16137        }
16138
16139        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16140            if (origin.staged) {
16141                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16142                codeFile = origin.file;
16143                resourceFile = origin.file;
16144                return PackageManager.INSTALL_SUCCEEDED;
16145            }
16146
16147            try {
16148                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16149                final File tempDir =
16150                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16151                codeFile = tempDir;
16152                resourceFile = tempDir;
16153            } catch (IOException e) {
16154                Slog.w(TAG, "Failed to create copy file: " + e);
16155                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16156            }
16157
16158            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16159                @Override
16160                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16161                    if (!FileUtils.isValidExtFilename(name)) {
16162                        throw new IllegalArgumentException("Invalid filename: " + name);
16163                    }
16164                    try {
16165                        final File file = new File(codeFile, name);
16166                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16167                                O_RDWR | O_CREAT, 0644);
16168                        Os.chmod(file.getAbsolutePath(), 0644);
16169                        return new ParcelFileDescriptor(fd);
16170                    } catch (ErrnoException e) {
16171                        throw new RemoteException("Failed to open: " + e.getMessage());
16172                    }
16173                }
16174            };
16175
16176            int ret = PackageManager.INSTALL_SUCCEEDED;
16177            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16178            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16179                Slog.e(TAG, "Failed to copy package");
16180                return ret;
16181            }
16182
16183            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16184            NativeLibraryHelper.Handle handle = null;
16185            try {
16186                handle = NativeLibraryHelper.Handle.create(codeFile);
16187                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16188                        abiOverride);
16189            } catch (IOException e) {
16190                Slog.e(TAG, "Copying native libraries failed", e);
16191                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16192            } finally {
16193                IoUtils.closeQuietly(handle);
16194            }
16195
16196            return ret;
16197        }
16198
16199        int doPreInstall(int status) {
16200            if (status != PackageManager.INSTALL_SUCCEEDED) {
16201                cleanUp();
16202            }
16203            return status;
16204        }
16205
16206        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16207            if (status != PackageManager.INSTALL_SUCCEEDED) {
16208                cleanUp();
16209                return false;
16210            }
16211
16212            final File targetDir = codeFile.getParentFile();
16213            final File beforeCodeFile = codeFile;
16214            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16215
16216            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16217            try {
16218                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16219            } catch (ErrnoException e) {
16220                Slog.w(TAG, "Failed to rename", e);
16221                return false;
16222            }
16223
16224            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16225                Slog.w(TAG, "Failed to restorecon");
16226                return false;
16227            }
16228
16229            // Reflect the rename internally
16230            codeFile = afterCodeFile;
16231            resourceFile = afterCodeFile;
16232
16233            // Reflect the rename in scanned details
16234            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16235            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16236                    afterCodeFile, pkg.baseCodePath));
16237            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16238                    afterCodeFile, pkg.splitCodePaths));
16239
16240            // Reflect the rename in app info
16241            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16242            pkg.setApplicationInfoCodePath(pkg.codePath);
16243            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16244            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16245            pkg.setApplicationInfoResourcePath(pkg.codePath);
16246            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16247            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16248
16249            return true;
16250        }
16251
16252        int doPostInstall(int status, int uid) {
16253            if (status != PackageManager.INSTALL_SUCCEEDED) {
16254                cleanUp();
16255            }
16256            return status;
16257        }
16258
16259        @Override
16260        String getCodePath() {
16261            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16262        }
16263
16264        @Override
16265        String getResourcePath() {
16266            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16267        }
16268
16269        private boolean cleanUp() {
16270            if (codeFile == null || !codeFile.exists()) {
16271                return false;
16272            }
16273
16274            removeCodePathLI(codeFile);
16275
16276            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16277                resourceFile.delete();
16278            }
16279
16280            return true;
16281        }
16282
16283        void cleanUpResourcesLI() {
16284            // Try enumerating all code paths before deleting
16285            List<String> allCodePaths = Collections.EMPTY_LIST;
16286            if (codeFile != null && codeFile.exists()) {
16287                try {
16288                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16289                    allCodePaths = pkg.getAllCodePaths();
16290                } catch (PackageParserException e) {
16291                    // Ignored; we tried our best
16292                }
16293            }
16294
16295            cleanUp();
16296            removeDexFiles(allCodePaths, instructionSets);
16297        }
16298
16299        boolean doPostDeleteLI(boolean delete) {
16300            // XXX err, shouldn't we respect the delete flag?
16301            cleanUpResourcesLI();
16302            return true;
16303        }
16304    }
16305
16306    private boolean isAsecExternal(String cid) {
16307        final String asecPath = PackageHelper.getSdFilesystem(cid);
16308        return !asecPath.startsWith(mAsecInternalPath);
16309    }
16310
16311    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16312            PackageManagerException {
16313        if (copyRet < 0) {
16314            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16315                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16316                throw new PackageManagerException(copyRet, message);
16317            }
16318        }
16319    }
16320
16321    /**
16322     * Extract the StorageManagerService "container ID" from the full code path of an
16323     * .apk.
16324     */
16325    static String cidFromCodePath(String fullCodePath) {
16326        int eidx = fullCodePath.lastIndexOf("/");
16327        String subStr1 = fullCodePath.substring(0, eidx);
16328        int sidx = subStr1.lastIndexOf("/");
16329        return subStr1.substring(sidx+1, eidx);
16330    }
16331
16332    /**
16333     * Logic to handle installation of ASEC applications, including copying and
16334     * renaming logic.
16335     */
16336    class AsecInstallArgs extends InstallArgs {
16337        static final String RES_FILE_NAME = "pkg.apk";
16338        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16339
16340        String cid;
16341        String packagePath;
16342        String resourcePath;
16343
16344        /** New install */
16345        AsecInstallArgs(InstallParams params) {
16346            super(params.origin, params.move, params.observer, params.installFlags,
16347                    params.installerPackageName, params.volumeUuid,
16348                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16349                    params.grantedRuntimePermissions,
16350                    params.traceMethod, params.traceCookie, params.certificates,
16351                    params.installReason);
16352        }
16353
16354        /** Existing install */
16355        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16356                        boolean isExternal, boolean isForwardLocked) {
16357            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16358                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16359                    instructionSets, null, null, null, 0, null /*certificates*/,
16360                    PackageManager.INSTALL_REASON_UNKNOWN);
16361            // Hackily pretend we're still looking at a full code path
16362            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16363                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16364            }
16365
16366            // Extract cid from fullCodePath
16367            int eidx = fullCodePath.lastIndexOf("/");
16368            String subStr1 = fullCodePath.substring(0, eidx);
16369            int sidx = subStr1.lastIndexOf("/");
16370            cid = subStr1.substring(sidx+1, eidx);
16371            setMountPath(subStr1);
16372        }
16373
16374        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16375            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16376                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16377                    instructionSets, null, null, null, 0, null /*certificates*/,
16378                    PackageManager.INSTALL_REASON_UNKNOWN);
16379            this.cid = cid;
16380            setMountPath(PackageHelper.getSdDir(cid));
16381        }
16382
16383        void createCopyFile() {
16384            cid = mInstallerService.allocateExternalStageCidLegacy();
16385        }
16386
16387        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16388            if (origin.staged && origin.cid != null) {
16389                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16390                cid = origin.cid;
16391                setMountPath(PackageHelper.getSdDir(cid));
16392                return PackageManager.INSTALL_SUCCEEDED;
16393            }
16394
16395            if (temp) {
16396                createCopyFile();
16397            } else {
16398                /*
16399                 * Pre-emptively destroy the container since it's destroyed if
16400                 * copying fails due to it existing anyway.
16401                 */
16402                PackageHelper.destroySdDir(cid);
16403            }
16404
16405            final String newMountPath = imcs.copyPackageToContainer(
16406                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16407                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16408
16409            if (newMountPath != null) {
16410                setMountPath(newMountPath);
16411                return PackageManager.INSTALL_SUCCEEDED;
16412            } else {
16413                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16414            }
16415        }
16416
16417        @Override
16418        String getCodePath() {
16419            return packagePath;
16420        }
16421
16422        @Override
16423        String getResourcePath() {
16424            return resourcePath;
16425        }
16426
16427        int doPreInstall(int status) {
16428            if (status != PackageManager.INSTALL_SUCCEEDED) {
16429                // Destroy container
16430                PackageHelper.destroySdDir(cid);
16431            } else {
16432                boolean mounted = PackageHelper.isContainerMounted(cid);
16433                if (!mounted) {
16434                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16435                            Process.SYSTEM_UID);
16436                    if (newMountPath != null) {
16437                        setMountPath(newMountPath);
16438                    } else {
16439                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16440                    }
16441                }
16442            }
16443            return status;
16444        }
16445
16446        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16447            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16448            String newMountPath = null;
16449            if (PackageHelper.isContainerMounted(cid)) {
16450                // Unmount the container
16451                if (!PackageHelper.unMountSdDir(cid)) {
16452                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16453                    return false;
16454                }
16455            }
16456            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16457                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16458                        " which might be stale. Will try to clean up.");
16459                // Clean up the stale container and proceed to recreate.
16460                if (!PackageHelper.destroySdDir(newCacheId)) {
16461                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16462                    return false;
16463                }
16464                // Successfully cleaned up stale container. Try to rename again.
16465                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16466                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16467                            + " inspite of cleaning it up.");
16468                    return false;
16469                }
16470            }
16471            if (!PackageHelper.isContainerMounted(newCacheId)) {
16472                Slog.w(TAG, "Mounting container " + newCacheId);
16473                newMountPath = PackageHelper.mountSdDir(newCacheId,
16474                        getEncryptKey(), Process.SYSTEM_UID);
16475            } else {
16476                newMountPath = PackageHelper.getSdDir(newCacheId);
16477            }
16478            if (newMountPath == null) {
16479                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16480                return false;
16481            }
16482            Log.i(TAG, "Succesfully renamed " + cid +
16483                    " to " + newCacheId +
16484                    " at new path: " + newMountPath);
16485            cid = newCacheId;
16486
16487            final File beforeCodeFile = new File(packagePath);
16488            setMountPath(newMountPath);
16489            final File afterCodeFile = new File(packagePath);
16490
16491            // Reflect the rename in scanned details
16492            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16493            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16494                    afterCodeFile, pkg.baseCodePath));
16495            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16496                    afterCodeFile, pkg.splitCodePaths));
16497
16498            // Reflect the rename in app info
16499            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16500            pkg.setApplicationInfoCodePath(pkg.codePath);
16501            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16502            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16503            pkg.setApplicationInfoResourcePath(pkg.codePath);
16504            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16505            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16506
16507            return true;
16508        }
16509
16510        private void setMountPath(String mountPath) {
16511            final File mountFile = new File(mountPath);
16512
16513            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16514            if (monolithicFile.exists()) {
16515                packagePath = monolithicFile.getAbsolutePath();
16516                if (isFwdLocked()) {
16517                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16518                } else {
16519                    resourcePath = packagePath;
16520                }
16521            } else {
16522                packagePath = mountFile.getAbsolutePath();
16523                resourcePath = packagePath;
16524            }
16525        }
16526
16527        int doPostInstall(int status, int uid) {
16528            if (status != PackageManager.INSTALL_SUCCEEDED) {
16529                cleanUp();
16530            } else {
16531                final int groupOwner;
16532                final String protectedFile;
16533                if (isFwdLocked()) {
16534                    groupOwner = UserHandle.getSharedAppGid(uid);
16535                    protectedFile = RES_FILE_NAME;
16536                } else {
16537                    groupOwner = -1;
16538                    protectedFile = null;
16539                }
16540
16541                if (uid < Process.FIRST_APPLICATION_UID
16542                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16543                    Slog.e(TAG, "Failed to finalize " + cid);
16544                    PackageHelper.destroySdDir(cid);
16545                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16546                }
16547
16548                boolean mounted = PackageHelper.isContainerMounted(cid);
16549                if (!mounted) {
16550                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16551                }
16552            }
16553            return status;
16554        }
16555
16556        private void cleanUp() {
16557            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16558
16559            // Destroy secure container
16560            PackageHelper.destroySdDir(cid);
16561        }
16562
16563        private List<String> getAllCodePaths() {
16564            final File codeFile = new File(getCodePath());
16565            if (codeFile != null && codeFile.exists()) {
16566                try {
16567                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16568                    return pkg.getAllCodePaths();
16569                } catch (PackageParserException e) {
16570                    // Ignored; we tried our best
16571                }
16572            }
16573            return Collections.EMPTY_LIST;
16574        }
16575
16576        void cleanUpResourcesLI() {
16577            // Enumerate all code paths before deleting
16578            cleanUpResourcesLI(getAllCodePaths());
16579        }
16580
16581        private void cleanUpResourcesLI(List<String> allCodePaths) {
16582            cleanUp();
16583            removeDexFiles(allCodePaths, instructionSets);
16584        }
16585
16586        String getPackageName() {
16587            return getAsecPackageName(cid);
16588        }
16589
16590        boolean doPostDeleteLI(boolean delete) {
16591            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16592            final List<String> allCodePaths = getAllCodePaths();
16593            boolean mounted = PackageHelper.isContainerMounted(cid);
16594            if (mounted) {
16595                // Unmount first
16596                if (PackageHelper.unMountSdDir(cid)) {
16597                    mounted = false;
16598                }
16599            }
16600            if (!mounted && delete) {
16601                cleanUpResourcesLI(allCodePaths);
16602            }
16603            return !mounted;
16604        }
16605
16606        @Override
16607        int doPreCopy() {
16608            if (isFwdLocked()) {
16609                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16610                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16611                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16612                }
16613            }
16614
16615            return PackageManager.INSTALL_SUCCEEDED;
16616        }
16617
16618        @Override
16619        int doPostCopy(int uid) {
16620            if (isFwdLocked()) {
16621                if (uid < Process.FIRST_APPLICATION_UID
16622                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16623                                RES_FILE_NAME)) {
16624                    Slog.e(TAG, "Failed to finalize " + cid);
16625                    PackageHelper.destroySdDir(cid);
16626                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16627                }
16628            }
16629
16630            return PackageManager.INSTALL_SUCCEEDED;
16631        }
16632    }
16633
16634    /**
16635     * Logic to handle movement of existing installed applications.
16636     */
16637    class MoveInstallArgs extends InstallArgs {
16638        private File codeFile;
16639        private File resourceFile;
16640
16641        /** New install */
16642        MoveInstallArgs(InstallParams params) {
16643            super(params.origin, params.move, params.observer, params.installFlags,
16644                    params.installerPackageName, params.volumeUuid,
16645                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16646                    params.grantedRuntimePermissions,
16647                    params.traceMethod, params.traceCookie, params.certificates,
16648                    params.installReason);
16649        }
16650
16651        int copyApk(IMediaContainerService imcs, boolean temp) {
16652            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16653                    + move.fromUuid + " to " + move.toUuid);
16654            synchronized (mInstaller) {
16655                try {
16656                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16657                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16658                } catch (InstallerException e) {
16659                    Slog.w(TAG, "Failed to move app", e);
16660                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16661                }
16662            }
16663
16664            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16665            resourceFile = codeFile;
16666            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16667
16668            return PackageManager.INSTALL_SUCCEEDED;
16669        }
16670
16671        int doPreInstall(int status) {
16672            if (status != PackageManager.INSTALL_SUCCEEDED) {
16673                cleanUp(move.toUuid);
16674            }
16675            return status;
16676        }
16677
16678        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16679            if (status != PackageManager.INSTALL_SUCCEEDED) {
16680                cleanUp(move.toUuid);
16681                return false;
16682            }
16683
16684            // Reflect the move in app info
16685            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16686            pkg.setApplicationInfoCodePath(pkg.codePath);
16687            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16688            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16689            pkg.setApplicationInfoResourcePath(pkg.codePath);
16690            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16691            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16692
16693            return true;
16694        }
16695
16696        int doPostInstall(int status, int uid) {
16697            if (status == PackageManager.INSTALL_SUCCEEDED) {
16698                cleanUp(move.fromUuid);
16699            } else {
16700                cleanUp(move.toUuid);
16701            }
16702            return status;
16703        }
16704
16705        @Override
16706        String getCodePath() {
16707            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16708        }
16709
16710        @Override
16711        String getResourcePath() {
16712            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16713        }
16714
16715        private boolean cleanUp(String volumeUuid) {
16716            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16717                    move.dataAppName);
16718            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16719            final int[] userIds = sUserManager.getUserIds();
16720            synchronized (mInstallLock) {
16721                // Clean up both app data and code
16722                // All package moves are frozen until finished
16723                for (int userId : userIds) {
16724                    try {
16725                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16726                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16727                    } catch (InstallerException e) {
16728                        Slog.w(TAG, String.valueOf(e));
16729                    }
16730                }
16731                removeCodePathLI(codeFile);
16732            }
16733            return true;
16734        }
16735
16736        void cleanUpResourcesLI() {
16737            throw new UnsupportedOperationException();
16738        }
16739
16740        boolean doPostDeleteLI(boolean delete) {
16741            throw new UnsupportedOperationException();
16742        }
16743    }
16744
16745    static String getAsecPackageName(String packageCid) {
16746        int idx = packageCid.lastIndexOf("-");
16747        if (idx == -1) {
16748            return packageCid;
16749        }
16750        return packageCid.substring(0, idx);
16751    }
16752
16753    // Utility method used to create code paths based on package name and available index.
16754    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16755        String idxStr = "";
16756        int idx = 1;
16757        // Fall back to default value of idx=1 if prefix is not
16758        // part of oldCodePath
16759        if (oldCodePath != null) {
16760            String subStr = oldCodePath;
16761            // Drop the suffix right away
16762            if (suffix != null && subStr.endsWith(suffix)) {
16763                subStr = subStr.substring(0, subStr.length() - suffix.length());
16764            }
16765            // If oldCodePath already contains prefix find out the
16766            // ending index to either increment or decrement.
16767            int sidx = subStr.lastIndexOf(prefix);
16768            if (sidx != -1) {
16769                subStr = subStr.substring(sidx + prefix.length());
16770                if (subStr != null) {
16771                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16772                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16773                    }
16774                    try {
16775                        idx = Integer.parseInt(subStr);
16776                        if (idx <= 1) {
16777                            idx++;
16778                        } else {
16779                            idx--;
16780                        }
16781                    } catch(NumberFormatException e) {
16782                    }
16783                }
16784            }
16785        }
16786        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16787        return prefix + idxStr;
16788    }
16789
16790    private File getNextCodePath(File targetDir, String packageName) {
16791        File result;
16792        SecureRandom random = new SecureRandom();
16793        byte[] bytes = new byte[16];
16794        do {
16795            random.nextBytes(bytes);
16796            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16797            result = new File(targetDir, packageName + "-" + suffix);
16798        } while (result.exists());
16799        return result;
16800    }
16801
16802    // Utility method that returns the relative package path with respect
16803    // to the installation directory. Like say for /data/data/com.test-1.apk
16804    // string com.test-1 is returned.
16805    static String deriveCodePathName(String codePath) {
16806        if (codePath == null) {
16807            return null;
16808        }
16809        final File codeFile = new File(codePath);
16810        final String name = codeFile.getName();
16811        if (codeFile.isDirectory()) {
16812            return name;
16813        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16814            final int lastDot = name.lastIndexOf('.');
16815            return name.substring(0, lastDot);
16816        } else {
16817            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16818            return null;
16819        }
16820    }
16821
16822    static class PackageInstalledInfo {
16823        String name;
16824        int uid;
16825        // The set of users that originally had this package installed.
16826        int[] origUsers;
16827        // The set of users that now have this package installed.
16828        int[] newUsers;
16829        PackageParser.Package pkg;
16830        int returnCode;
16831        String returnMsg;
16832        PackageRemovedInfo removedInfo;
16833        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16834
16835        public void setError(int code, String msg) {
16836            setReturnCode(code);
16837            setReturnMessage(msg);
16838            Slog.w(TAG, msg);
16839        }
16840
16841        public void setError(String msg, PackageParserException e) {
16842            setReturnCode(e.error);
16843            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16844            Slog.w(TAG, msg, e);
16845        }
16846
16847        public void setError(String msg, PackageManagerException e) {
16848            returnCode = e.error;
16849            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16850            Slog.w(TAG, msg, e);
16851        }
16852
16853        public void setReturnCode(int returnCode) {
16854            this.returnCode = returnCode;
16855            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16856            for (int i = 0; i < childCount; i++) {
16857                addedChildPackages.valueAt(i).returnCode = returnCode;
16858            }
16859        }
16860
16861        private void setReturnMessage(String returnMsg) {
16862            this.returnMsg = returnMsg;
16863            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16864            for (int i = 0; i < childCount; i++) {
16865                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16866            }
16867        }
16868
16869        // In some error cases we want to convey more info back to the observer
16870        String origPackage;
16871        String origPermission;
16872    }
16873
16874    /*
16875     * Install a non-existing package.
16876     */
16877    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16878            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16879            PackageInstalledInfo res, int installReason) {
16880        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16881
16882        // Remember this for later, in case we need to rollback this install
16883        String pkgName = pkg.packageName;
16884
16885        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16886
16887        synchronized(mPackages) {
16888            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16889            if (renamedPackage != null) {
16890                // A package with the same name is already installed, though
16891                // it has been renamed to an older name.  The package we
16892                // are trying to install should be installed as an update to
16893                // the existing one, but that has not been requested, so bail.
16894                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16895                        + " without first uninstalling package running as "
16896                        + renamedPackage);
16897                return;
16898            }
16899            if (mPackages.containsKey(pkgName)) {
16900                // Don't allow installation over an existing package with the same name.
16901                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16902                        + " without first uninstalling.");
16903                return;
16904            }
16905        }
16906
16907        try {
16908            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16909                    System.currentTimeMillis(), user);
16910
16911            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16912
16913            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16914                prepareAppDataAfterInstallLIF(newPackage);
16915
16916            } else {
16917                // Remove package from internal structures, but keep around any
16918                // data that might have already existed
16919                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16920                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16921            }
16922        } catch (PackageManagerException e) {
16923            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16924        }
16925
16926        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16927    }
16928
16929    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16930        // Can't rotate keys during boot or if sharedUser.
16931        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16932                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16933            return false;
16934        }
16935        // app is using upgradeKeySets; make sure all are valid
16936        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16937        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16938        for (int i = 0; i < upgradeKeySets.length; i++) {
16939            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16940                Slog.wtf(TAG, "Package "
16941                         + (oldPs.name != null ? oldPs.name : "<null>")
16942                         + " contains upgrade-key-set reference to unknown key-set: "
16943                         + upgradeKeySets[i]
16944                         + " reverting to signatures check.");
16945                return false;
16946            }
16947        }
16948        return true;
16949    }
16950
16951    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16952        // Upgrade keysets are being used.  Determine if new package has a superset of the
16953        // required keys.
16954        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16955        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16956        for (int i = 0; i < upgradeKeySets.length; i++) {
16957            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16958            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16959                return true;
16960            }
16961        }
16962        return false;
16963    }
16964
16965    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16966        try (DigestInputStream digestStream =
16967                new DigestInputStream(new FileInputStream(file), digest)) {
16968            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16969        }
16970    }
16971
16972    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16973            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16974            int installReason) {
16975        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16976
16977        final PackageParser.Package oldPackage;
16978        final PackageSetting ps;
16979        final String pkgName = pkg.packageName;
16980        final int[] allUsers;
16981        final int[] installedUsers;
16982
16983        synchronized(mPackages) {
16984            oldPackage = mPackages.get(pkgName);
16985            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16986
16987            // don't allow upgrade to target a release SDK from a pre-release SDK
16988            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16989                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16990            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16991                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16992            if (oldTargetsPreRelease
16993                    && !newTargetsPreRelease
16994                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16995                Slog.w(TAG, "Can't install package targeting released sdk");
16996                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16997                return;
16998            }
16999
17000            ps = mSettings.mPackages.get(pkgName);
17001
17002            // verify signatures are valid
17003            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17004                if (!checkUpgradeKeySetLP(ps, pkg)) {
17005                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17006                            "New package not signed by keys specified by upgrade-keysets: "
17007                                    + pkgName);
17008                    return;
17009                }
17010            } else {
17011                // default to original signature matching
17012                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17013                        != PackageManager.SIGNATURE_MATCH) {
17014                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17015                            "New package has a different signature: " + pkgName);
17016                    return;
17017                }
17018            }
17019
17020            // don't allow a system upgrade unless the upgrade hash matches
17021            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17022                byte[] digestBytes = null;
17023                try {
17024                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17025                    updateDigest(digest, new File(pkg.baseCodePath));
17026                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17027                        for (String path : pkg.splitCodePaths) {
17028                            updateDigest(digest, new File(path));
17029                        }
17030                    }
17031                    digestBytes = digest.digest();
17032                } catch (NoSuchAlgorithmException | IOException e) {
17033                    res.setError(INSTALL_FAILED_INVALID_APK,
17034                            "Could not compute hash: " + pkgName);
17035                    return;
17036                }
17037                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17038                    res.setError(INSTALL_FAILED_INVALID_APK,
17039                            "New package fails restrict-update check: " + pkgName);
17040                    return;
17041                }
17042                // retain upgrade restriction
17043                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17044            }
17045
17046            // Check for shared user id changes
17047            String invalidPackageName =
17048                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17049            if (invalidPackageName != null) {
17050                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17051                        "Package " + invalidPackageName + " tried to change user "
17052                                + oldPackage.mSharedUserId);
17053                return;
17054            }
17055
17056            // In case of rollback, remember per-user/profile install state
17057            allUsers = sUserManager.getUserIds();
17058            installedUsers = ps.queryInstalledUsers(allUsers, true);
17059
17060            // don't allow an upgrade from full to ephemeral
17061            if (isInstantApp) {
17062                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17063                    for (int currentUser : allUsers) {
17064                        if (!ps.getInstantApp(currentUser)) {
17065                            // can't downgrade from full to instant
17066                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17067                                    + " for user: " + currentUser);
17068                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17069                            return;
17070                        }
17071                    }
17072                } else if (!ps.getInstantApp(user.getIdentifier())) {
17073                    // can't downgrade from full to instant
17074                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17075                            + " for user: " + user.getIdentifier());
17076                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17077                    return;
17078                }
17079            }
17080        }
17081
17082        // Update what is removed
17083        res.removedInfo = new PackageRemovedInfo(this);
17084        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17085        res.removedInfo.removedPackage = oldPackage.packageName;
17086        res.removedInfo.installerPackageName = ps.installerPackageName;
17087        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17088        res.removedInfo.isUpdate = true;
17089        res.removedInfo.origUsers = installedUsers;
17090        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17091        for (int i = 0; i < installedUsers.length; i++) {
17092            final int userId = installedUsers[i];
17093            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17094        }
17095
17096        final int childCount = (oldPackage.childPackages != null)
17097                ? oldPackage.childPackages.size() : 0;
17098        for (int i = 0; i < childCount; i++) {
17099            boolean childPackageUpdated = false;
17100            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17101            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17102            if (res.addedChildPackages != null) {
17103                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17104                if (childRes != null) {
17105                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17106                    childRes.removedInfo.removedPackage = childPkg.packageName;
17107                    if (childPs != null) {
17108                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17109                    }
17110                    childRes.removedInfo.isUpdate = true;
17111                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17112                    childPackageUpdated = true;
17113                }
17114            }
17115            if (!childPackageUpdated) {
17116                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17117                childRemovedRes.removedPackage = childPkg.packageName;
17118                if (childPs != null) {
17119                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17120                }
17121                childRemovedRes.isUpdate = false;
17122                childRemovedRes.dataRemoved = true;
17123                synchronized (mPackages) {
17124                    if (childPs != null) {
17125                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17126                    }
17127                }
17128                if (res.removedInfo.removedChildPackages == null) {
17129                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17130                }
17131                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17132            }
17133        }
17134
17135        boolean sysPkg = (isSystemApp(oldPackage));
17136        if (sysPkg) {
17137            // Set the system/privileged flags as needed
17138            final boolean privileged =
17139                    (oldPackage.applicationInfo.privateFlags
17140                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17141            final int systemPolicyFlags = policyFlags
17142                    | PackageParser.PARSE_IS_SYSTEM
17143                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17144
17145            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17146                    user, allUsers, installerPackageName, res, installReason);
17147        } else {
17148            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17149                    user, allUsers, installerPackageName, res, installReason);
17150        }
17151    }
17152
17153    @Override
17154    public List<String> getPreviousCodePaths(String packageName) {
17155        final int callingUid = Binder.getCallingUid();
17156        final List<String> result = new ArrayList<>();
17157        if (getInstantAppPackageName(callingUid) != null) {
17158            return result;
17159        }
17160        final PackageSetting ps = mSettings.mPackages.get(packageName);
17161        if (ps != null
17162                && ps.oldCodePaths != null
17163                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17164            result.addAll(ps.oldCodePaths);
17165        }
17166        return result;
17167    }
17168
17169    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17170            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17171            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17172            int installReason) {
17173        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17174                + deletedPackage);
17175
17176        String pkgName = deletedPackage.packageName;
17177        boolean deletedPkg = true;
17178        boolean addedPkg = false;
17179        boolean updatedSettings = false;
17180        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17181        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17182                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17183
17184        final long origUpdateTime = (pkg.mExtras != null)
17185                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17186
17187        // First delete the existing package while retaining the data directory
17188        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17189                res.removedInfo, true, pkg)) {
17190            // If the existing package wasn't successfully deleted
17191            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17192            deletedPkg = false;
17193        } else {
17194            // Successfully deleted the old package; proceed with replace.
17195
17196            // If deleted package lived in a container, give users a chance to
17197            // relinquish resources before killing.
17198            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17199                if (DEBUG_INSTALL) {
17200                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17201                }
17202                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17203                final ArrayList<String> pkgList = new ArrayList<String>(1);
17204                pkgList.add(deletedPackage.applicationInfo.packageName);
17205                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17206            }
17207
17208            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17209                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17210            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17211
17212            try {
17213                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17214                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17215                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17216                        installReason);
17217
17218                // Update the in-memory copy of the previous code paths.
17219                PackageSetting ps = mSettings.mPackages.get(pkgName);
17220                if (!killApp) {
17221                    if (ps.oldCodePaths == null) {
17222                        ps.oldCodePaths = new ArraySet<>();
17223                    }
17224                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17225                    if (deletedPackage.splitCodePaths != null) {
17226                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17227                    }
17228                } else {
17229                    ps.oldCodePaths = null;
17230                }
17231                if (ps.childPackageNames != null) {
17232                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17233                        final String childPkgName = ps.childPackageNames.get(i);
17234                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17235                        childPs.oldCodePaths = ps.oldCodePaths;
17236                    }
17237                }
17238                // set instant app status, but, only if it's explicitly specified
17239                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17240                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17241                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17242                prepareAppDataAfterInstallLIF(newPackage);
17243                addedPkg = true;
17244                mDexManager.notifyPackageUpdated(newPackage.packageName,
17245                        newPackage.baseCodePath, newPackage.splitCodePaths);
17246            } catch (PackageManagerException e) {
17247                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17248            }
17249        }
17250
17251        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17252            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17253
17254            // Revert all internal state mutations and added folders for the failed install
17255            if (addedPkg) {
17256                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17257                        res.removedInfo, true, null);
17258            }
17259
17260            // Restore the old package
17261            if (deletedPkg) {
17262                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17263                File restoreFile = new File(deletedPackage.codePath);
17264                // Parse old package
17265                boolean oldExternal = isExternal(deletedPackage);
17266                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17267                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17268                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17269                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17270                try {
17271                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17272                            null);
17273                } catch (PackageManagerException e) {
17274                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17275                            + e.getMessage());
17276                    return;
17277                }
17278
17279                synchronized (mPackages) {
17280                    // Ensure the installer package name up to date
17281                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17282
17283                    // Update permissions for restored package
17284                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17285
17286                    mSettings.writeLPr();
17287                }
17288
17289                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17290            }
17291        } else {
17292            synchronized (mPackages) {
17293                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17294                if (ps != null) {
17295                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17296                    if (res.removedInfo.removedChildPackages != null) {
17297                        final int childCount = res.removedInfo.removedChildPackages.size();
17298                        // Iterate in reverse as we may modify the collection
17299                        for (int i = childCount - 1; i >= 0; i--) {
17300                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17301                            if (res.addedChildPackages.containsKey(childPackageName)) {
17302                                res.removedInfo.removedChildPackages.removeAt(i);
17303                            } else {
17304                                PackageRemovedInfo childInfo = res.removedInfo
17305                                        .removedChildPackages.valueAt(i);
17306                                childInfo.removedForAllUsers = mPackages.get(
17307                                        childInfo.removedPackage) == null;
17308                            }
17309                        }
17310                    }
17311                }
17312            }
17313        }
17314    }
17315
17316    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17317            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17318            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17319            int installReason) {
17320        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17321                + ", old=" + deletedPackage);
17322
17323        final boolean disabledSystem;
17324
17325        // Remove existing system package
17326        removePackageLI(deletedPackage, true);
17327
17328        synchronized (mPackages) {
17329            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17330        }
17331        if (!disabledSystem) {
17332            // We didn't need to disable the .apk as a current system package,
17333            // which means we are replacing another update that is already
17334            // installed.  We need to make sure to delete the older one's .apk.
17335            res.removedInfo.args = createInstallArgsForExisting(0,
17336                    deletedPackage.applicationInfo.getCodePath(),
17337                    deletedPackage.applicationInfo.getResourcePath(),
17338                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17339        } else {
17340            res.removedInfo.args = null;
17341        }
17342
17343        // Successfully disabled the old package. Now proceed with re-installation
17344        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17345                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17346        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17347
17348        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17349        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17350                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17351
17352        PackageParser.Package newPackage = null;
17353        try {
17354            // Add the package to the internal data structures
17355            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17356
17357            // Set the update and install times
17358            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17359            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17360                    System.currentTimeMillis());
17361
17362            // Update the package dynamic state if succeeded
17363            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17364                // Now that the install succeeded make sure we remove data
17365                // directories for any child package the update removed.
17366                final int deletedChildCount = (deletedPackage.childPackages != null)
17367                        ? deletedPackage.childPackages.size() : 0;
17368                final int newChildCount = (newPackage.childPackages != null)
17369                        ? newPackage.childPackages.size() : 0;
17370                for (int i = 0; i < deletedChildCount; i++) {
17371                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17372                    boolean childPackageDeleted = true;
17373                    for (int j = 0; j < newChildCount; j++) {
17374                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17375                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17376                            childPackageDeleted = false;
17377                            break;
17378                        }
17379                    }
17380                    if (childPackageDeleted) {
17381                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17382                                deletedChildPkg.packageName);
17383                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17384                            PackageRemovedInfo removedChildRes = res.removedInfo
17385                                    .removedChildPackages.get(deletedChildPkg.packageName);
17386                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17387                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17388                        }
17389                    }
17390                }
17391
17392                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17393                        installReason);
17394                prepareAppDataAfterInstallLIF(newPackage);
17395
17396                mDexManager.notifyPackageUpdated(newPackage.packageName,
17397                            newPackage.baseCodePath, newPackage.splitCodePaths);
17398            }
17399        } catch (PackageManagerException e) {
17400            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17401            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17402        }
17403
17404        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17405            // Re installation failed. Restore old information
17406            // Remove new pkg information
17407            if (newPackage != null) {
17408                removeInstalledPackageLI(newPackage, true);
17409            }
17410            // Add back the old system package
17411            try {
17412                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17413            } catch (PackageManagerException e) {
17414                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17415            }
17416
17417            synchronized (mPackages) {
17418                if (disabledSystem) {
17419                    enableSystemPackageLPw(deletedPackage);
17420                }
17421
17422                // Ensure the installer package name up to date
17423                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17424
17425                // Update permissions for restored package
17426                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17427
17428                mSettings.writeLPr();
17429            }
17430
17431            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17432                    + " after failed upgrade");
17433        }
17434    }
17435
17436    /**
17437     * Checks whether the parent or any of the child packages have a change shared
17438     * user. For a package to be a valid update the shred users of the parent and
17439     * the children should match. We may later support changing child shared users.
17440     * @param oldPkg The updated package.
17441     * @param newPkg The update package.
17442     * @return The shared user that change between the versions.
17443     */
17444    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17445            PackageParser.Package newPkg) {
17446        // Check parent shared user
17447        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17448            return newPkg.packageName;
17449        }
17450        // Check child shared users
17451        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17452        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17453        for (int i = 0; i < newChildCount; i++) {
17454            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17455            // If this child was present, did it have the same shared user?
17456            for (int j = 0; j < oldChildCount; j++) {
17457                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17458                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17459                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17460                    return newChildPkg.packageName;
17461                }
17462            }
17463        }
17464        return null;
17465    }
17466
17467    private void removeNativeBinariesLI(PackageSetting ps) {
17468        // Remove the lib path for the parent package
17469        if (ps != null) {
17470            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17471            // Remove the lib path for the child packages
17472            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17473            for (int i = 0; i < childCount; i++) {
17474                PackageSetting childPs = null;
17475                synchronized (mPackages) {
17476                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17477                }
17478                if (childPs != null) {
17479                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17480                            .legacyNativeLibraryPathString);
17481                }
17482            }
17483        }
17484    }
17485
17486    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17487        // Enable the parent package
17488        mSettings.enableSystemPackageLPw(pkg.packageName);
17489        // Enable the child packages
17490        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17491        for (int i = 0; i < childCount; i++) {
17492            PackageParser.Package childPkg = pkg.childPackages.get(i);
17493            mSettings.enableSystemPackageLPw(childPkg.packageName);
17494        }
17495    }
17496
17497    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17498            PackageParser.Package newPkg) {
17499        // Disable the parent package (parent always replaced)
17500        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17501        // Disable the child packages
17502        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17503        for (int i = 0; i < childCount; i++) {
17504            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17505            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17506            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17507        }
17508        return disabled;
17509    }
17510
17511    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17512            String installerPackageName) {
17513        // Enable the parent package
17514        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17515        // Enable the child packages
17516        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17517        for (int i = 0; i < childCount; i++) {
17518            PackageParser.Package childPkg = pkg.childPackages.get(i);
17519            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17520        }
17521    }
17522
17523    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17524        // Collect all used permissions in the UID
17525        ArraySet<String> usedPermissions = new ArraySet<>();
17526        final int packageCount = su.packages.size();
17527        for (int i = 0; i < packageCount; i++) {
17528            PackageSetting ps = su.packages.valueAt(i);
17529            if (ps.pkg == null) {
17530                continue;
17531            }
17532            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17533            for (int j = 0; j < requestedPermCount; j++) {
17534                String permission = ps.pkg.requestedPermissions.get(j);
17535                BasePermission bp = mSettings.mPermissions.get(permission);
17536                if (bp != null) {
17537                    usedPermissions.add(permission);
17538                }
17539            }
17540        }
17541
17542        PermissionsState permissionsState = su.getPermissionsState();
17543        // Prune install permissions
17544        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17545        final int installPermCount = installPermStates.size();
17546        for (int i = installPermCount - 1; i >= 0;  i--) {
17547            PermissionState permissionState = installPermStates.get(i);
17548            if (!usedPermissions.contains(permissionState.getName())) {
17549                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17550                if (bp != null) {
17551                    permissionsState.revokeInstallPermission(bp);
17552                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17553                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17554                }
17555            }
17556        }
17557
17558        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17559
17560        // Prune runtime permissions
17561        for (int userId : allUserIds) {
17562            List<PermissionState> runtimePermStates = permissionsState
17563                    .getRuntimePermissionStates(userId);
17564            final int runtimePermCount = runtimePermStates.size();
17565            for (int i = runtimePermCount - 1; i >= 0; i--) {
17566                PermissionState permissionState = runtimePermStates.get(i);
17567                if (!usedPermissions.contains(permissionState.getName())) {
17568                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17569                    if (bp != null) {
17570                        permissionsState.revokeRuntimePermission(bp, userId);
17571                        permissionsState.updatePermissionFlags(bp, userId,
17572                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17573                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17574                                runtimePermissionChangedUserIds, userId);
17575                    }
17576                }
17577            }
17578        }
17579
17580        return runtimePermissionChangedUserIds;
17581    }
17582
17583    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17584            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17585        // Update the parent package setting
17586        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17587                res, user, installReason);
17588        // Update the child packages setting
17589        final int childCount = (newPackage.childPackages != null)
17590                ? newPackage.childPackages.size() : 0;
17591        for (int i = 0; i < childCount; i++) {
17592            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17593            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17594            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17595                    childRes.origUsers, childRes, user, installReason);
17596        }
17597    }
17598
17599    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17600            String installerPackageName, int[] allUsers, int[] installedForUsers,
17601            PackageInstalledInfo res, UserHandle user, int installReason) {
17602        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17603
17604        String pkgName = newPackage.packageName;
17605        synchronized (mPackages) {
17606            //write settings. the installStatus will be incomplete at this stage.
17607            //note that the new package setting would have already been
17608            //added to mPackages. It hasn't been persisted yet.
17609            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17610            // TODO: Remove this write? It's also written at the end of this method
17611            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17612            mSettings.writeLPr();
17613            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17614        }
17615
17616        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17617        synchronized (mPackages) {
17618            updatePermissionsLPw(newPackage.packageName, newPackage,
17619                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17620                            ? UPDATE_PERMISSIONS_ALL : 0));
17621            // For system-bundled packages, we assume that installing an upgraded version
17622            // of the package implies that the user actually wants to run that new code,
17623            // so we enable the package.
17624            PackageSetting ps = mSettings.mPackages.get(pkgName);
17625            final int userId = user.getIdentifier();
17626            if (ps != null) {
17627                if (isSystemApp(newPackage)) {
17628                    if (DEBUG_INSTALL) {
17629                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17630                    }
17631                    // Enable system package for requested users
17632                    if (res.origUsers != null) {
17633                        for (int origUserId : res.origUsers) {
17634                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17635                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17636                                        origUserId, installerPackageName);
17637                            }
17638                        }
17639                    }
17640                    // Also convey the prior install/uninstall state
17641                    if (allUsers != null && installedForUsers != null) {
17642                        for (int currentUserId : allUsers) {
17643                            final boolean installed = ArrayUtils.contains(
17644                                    installedForUsers, currentUserId);
17645                            if (DEBUG_INSTALL) {
17646                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17647                            }
17648                            ps.setInstalled(installed, currentUserId);
17649                        }
17650                        // these install state changes will be persisted in the
17651                        // upcoming call to mSettings.writeLPr().
17652                    }
17653                }
17654                // It's implied that when a user requests installation, they want the app to be
17655                // installed and enabled.
17656                if (userId != UserHandle.USER_ALL) {
17657                    ps.setInstalled(true, userId);
17658                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17659                }
17660
17661                // When replacing an existing package, preserve the original install reason for all
17662                // users that had the package installed before.
17663                final Set<Integer> previousUserIds = new ArraySet<>();
17664                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17665                    final int installReasonCount = res.removedInfo.installReasons.size();
17666                    for (int i = 0; i < installReasonCount; i++) {
17667                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17668                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17669                        ps.setInstallReason(previousInstallReason, previousUserId);
17670                        previousUserIds.add(previousUserId);
17671                    }
17672                }
17673
17674                // Set install reason for users that are having the package newly installed.
17675                if (userId == UserHandle.USER_ALL) {
17676                    for (int currentUserId : sUserManager.getUserIds()) {
17677                        if (!previousUserIds.contains(currentUserId)) {
17678                            ps.setInstallReason(installReason, currentUserId);
17679                        }
17680                    }
17681                } else if (!previousUserIds.contains(userId)) {
17682                    ps.setInstallReason(installReason, userId);
17683                }
17684                mSettings.writeKernelMappingLPr(ps);
17685            }
17686            res.name = pkgName;
17687            res.uid = newPackage.applicationInfo.uid;
17688            res.pkg = newPackage;
17689            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17690            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17691            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17692            //to update install status
17693            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17694            mSettings.writeLPr();
17695            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17696        }
17697
17698        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17699    }
17700
17701    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17702        try {
17703            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17704            installPackageLI(args, res);
17705        } finally {
17706            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17707        }
17708    }
17709
17710    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17711        final int installFlags = args.installFlags;
17712        final String installerPackageName = args.installerPackageName;
17713        final String volumeUuid = args.volumeUuid;
17714        final File tmpPackageFile = new File(args.getCodePath());
17715        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17716        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17717                || (args.volumeUuid != null));
17718        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17719        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17720        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17721        boolean replace = false;
17722        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17723        if (args.move != null) {
17724            // moving a complete application; perform an initial scan on the new install location
17725            scanFlags |= SCAN_INITIAL;
17726        }
17727        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17728            scanFlags |= SCAN_DONT_KILL_APP;
17729        }
17730        if (instantApp) {
17731            scanFlags |= SCAN_AS_INSTANT_APP;
17732        }
17733        if (fullApp) {
17734            scanFlags |= SCAN_AS_FULL_APP;
17735        }
17736
17737        // Result object to be returned
17738        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17739
17740        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17741
17742        // Sanity check
17743        if (instantApp && (forwardLocked || onExternal)) {
17744            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17745                    + " external=" + onExternal);
17746            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17747            return;
17748        }
17749
17750        // Retrieve PackageSettings and parse package
17751        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17752                | PackageParser.PARSE_ENFORCE_CODE
17753                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17754                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17755                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17756                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17757        PackageParser pp = new PackageParser();
17758        pp.setSeparateProcesses(mSeparateProcesses);
17759        pp.setDisplayMetrics(mMetrics);
17760        pp.setCallback(mPackageParserCallback);
17761
17762        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17763        final PackageParser.Package pkg;
17764        try {
17765            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17766        } catch (PackageParserException e) {
17767            res.setError("Failed parse during installPackageLI", e);
17768            return;
17769        } finally {
17770            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17771        }
17772
17773        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17774        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17775            Slog.w(TAG, "Instant app package " + pkg.packageName
17776                    + " does not target O, this will be a fatal error.");
17777            // STOPSHIP: Make this a fatal error
17778            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17779        }
17780        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17781            Slog.w(TAG, "Instant app package " + pkg.packageName
17782                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17783            // STOPSHIP: Make this a fatal error
17784            pkg.applicationInfo.targetSandboxVersion = 2;
17785        }
17786
17787        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17788            // Static shared libraries have synthetic package names
17789            renameStaticSharedLibraryPackage(pkg);
17790
17791            // No static shared libs on external storage
17792            if (onExternal) {
17793                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17794                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17795                        "Packages declaring static-shared libs cannot be updated");
17796                return;
17797            }
17798        }
17799
17800        // If we are installing a clustered package add results for the children
17801        if (pkg.childPackages != null) {
17802            synchronized (mPackages) {
17803                final int childCount = pkg.childPackages.size();
17804                for (int i = 0; i < childCount; i++) {
17805                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17806                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17807                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17808                    childRes.pkg = childPkg;
17809                    childRes.name = childPkg.packageName;
17810                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17811                    if (childPs != null) {
17812                        childRes.origUsers = childPs.queryInstalledUsers(
17813                                sUserManager.getUserIds(), true);
17814                    }
17815                    if ((mPackages.containsKey(childPkg.packageName))) {
17816                        childRes.removedInfo = new PackageRemovedInfo(this);
17817                        childRes.removedInfo.removedPackage = childPkg.packageName;
17818                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17819                    }
17820                    if (res.addedChildPackages == null) {
17821                        res.addedChildPackages = new ArrayMap<>();
17822                    }
17823                    res.addedChildPackages.put(childPkg.packageName, childRes);
17824                }
17825            }
17826        }
17827
17828        // If package doesn't declare API override, mark that we have an install
17829        // time CPU ABI override.
17830        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17831            pkg.cpuAbiOverride = args.abiOverride;
17832        }
17833
17834        String pkgName = res.name = pkg.packageName;
17835        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17836            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17837                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17838                return;
17839            }
17840        }
17841
17842        try {
17843            // either use what we've been given or parse directly from the APK
17844            if (args.certificates != null) {
17845                try {
17846                    PackageParser.populateCertificates(pkg, args.certificates);
17847                } catch (PackageParserException e) {
17848                    // there was something wrong with the certificates we were given;
17849                    // try to pull them from the APK
17850                    PackageParser.collectCertificates(pkg, parseFlags);
17851                }
17852            } else {
17853                PackageParser.collectCertificates(pkg, parseFlags);
17854            }
17855        } catch (PackageParserException e) {
17856            res.setError("Failed collect during installPackageLI", e);
17857            return;
17858        }
17859
17860        // Get rid of all references to package scan path via parser.
17861        pp = null;
17862        String oldCodePath = null;
17863        boolean systemApp = false;
17864        synchronized (mPackages) {
17865            // Check if installing already existing package
17866            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17867                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17868                if (pkg.mOriginalPackages != null
17869                        && pkg.mOriginalPackages.contains(oldName)
17870                        && mPackages.containsKey(oldName)) {
17871                    // This package is derived from an original package,
17872                    // and this device has been updating from that original
17873                    // name.  We must continue using the original name, so
17874                    // rename the new package here.
17875                    pkg.setPackageName(oldName);
17876                    pkgName = pkg.packageName;
17877                    replace = true;
17878                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17879                            + oldName + " pkgName=" + pkgName);
17880                } else if (mPackages.containsKey(pkgName)) {
17881                    // This package, under its official name, already exists
17882                    // on the device; we should replace it.
17883                    replace = true;
17884                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17885                }
17886
17887                // Child packages are installed through the parent package
17888                if (pkg.parentPackage != null) {
17889                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17890                            "Package " + pkg.packageName + " is child of package "
17891                                    + pkg.parentPackage.parentPackage + ". Child packages "
17892                                    + "can be updated only through the parent package.");
17893                    return;
17894                }
17895
17896                if (replace) {
17897                    // Prevent apps opting out from runtime permissions
17898                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17899                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17900                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17901                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17902                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17903                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17904                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17905                                        + " doesn't support runtime permissions but the old"
17906                                        + " target SDK " + oldTargetSdk + " does.");
17907                        return;
17908                    }
17909                    // Prevent apps from downgrading their targetSandbox.
17910                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17911                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17912                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17913                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17914                                "Package " + pkg.packageName + " new target sandbox "
17915                                + newTargetSandbox + " is incompatible with the previous value of"
17916                                + oldTargetSandbox + ".");
17917                        return;
17918                    }
17919
17920                    // Prevent installing of child packages
17921                    if (oldPackage.parentPackage != null) {
17922                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17923                                "Package " + pkg.packageName + " is child of package "
17924                                        + oldPackage.parentPackage + ". Child packages "
17925                                        + "can be updated only through the parent package.");
17926                        return;
17927                    }
17928                }
17929            }
17930
17931            PackageSetting ps = mSettings.mPackages.get(pkgName);
17932            if (ps != null) {
17933                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17934
17935                // Static shared libs have same package with different versions where
17936                // we internally use a synthetic package name to allow multiple versions
17937                // of the same package, therefore we need to compare signatures against
17938                // the package setting for the latest library version.
17939                PackageSetting signatureCheckPs = ps;
17940                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17941                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17942                    if (libraryEntry != null) {
17943                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17944                    }
17945                }
17946
17947                // Quick sanity check that we're signed correctly if updating;
17948                // we'll check this again later when scanning, but we want to
17949                // bail early here before tripping over redefined permissions.
17950                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17951                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17952                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17953                                + pkg.packageName + " upgrade keys do not match the "
17954                                + "previously installed version");
17955                        return;
17956                    }
17957                } else {
17958                    try {
17959                        verifySignaturesLP(signatureCheckPs, pkg);
17960                    } catch (PackageManagerException e) {
17961                        res.setError(e.error, e.getMessage());
17962                        return;
17963                    }
17964                }
17965
17966                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17967                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17968                    systemApp = (ps.pkg.applicationInfo.flags &
17969                            ApplicationInfo.FLAG_SYSTEM) != 0;
17970                }
17971                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17972            }
17973
17974            int N = pkg.permissions.size();
17975            for (int i = N-1; i >= 0; i--) {
17976                PackageParser.Permission perm = pkg.permissions.get(i);
17977                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17978
17979                // Don't allow anyone but the system to define ephemeral permissions.
17980                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17981                        && !systemApp) {
17982                    Slog.w(TAG, "Non-System package " + pkg.packageName
17983                            + " attempting to delcare ephemeral permission "
17984                            + perm.info.name + "; Removing ephemeral.");
17985                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17986                }
17987                // Check whether the newly-scanned package wants to define an already-defined perm
17988                if (bp != null) {
17989                    // If the defining package is signed with our cert, it's okay.  This
17990                    // also includes the "updating the same package" case, of course.
17991                    // "updating same package" could also involve key-rotation.
17992                    final boolean sigsOk;
17993                    if (bp.sourcePackage.equals(pkg.packageName)
17994                            && (bp.packageSetting instanceof PackageSetting)
17995                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17996                                    scanFlags))) {
17997                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17998                    } else {
17999                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18000                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18001                    }
18002                    if (!sigsOk) {
18003                        // If the owning package is the system itself, we log but allow
18004                        // install to proceed; we fail the install on all other permission
18005                        // redefinitions.
18006                        if (!bp.sourcePackage.equals("android")) {
18007                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18008                                    + pkg.packageName + " attempting to redeclare permission "
18009                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18010                            res.origPermission = perm.info.name;
18011                            res.origPackage = bp.sourcePackage;
18012                            return;
18013                        } else {
18014                            Slog.w(TAG, "Package " + pkg.packageName
18015                                    + " attempting to redeclare system permission "
18016                                    + perm.info.name + "; ignoring new declaration");
18017                            pkg.permissions.remove(i);
18018                        }
18019                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18020                        // Prevent apps to change protection level to dangerous from any other
18021                        // type as this would allow a privilege escalation where an app adds a
18022                        // normal/signature permission in other app's group and later redefines
18023                        // it as dangerous leading to the group auto-grant.
18024                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18025                                == PermissionInfo.PROTECTION_DANGEROUS) {
18026                            if (bp != null && !bp.isRuntime()) {
18027                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18028                                        + "non-runtime permission " + perm.info.name
18029                                        + " to runtime; keeping old protection level");
18030                                perm.info.protectionLevel = bp.protectionLevel;
18031                            }
18032                        }
18033                    }
18034                }
18035            }
18036        }
18037
18038        if (systemApp) {
18039            if (onExternal) {
18040                // Abort update; system app can't be replaced with app on sdcard
18041                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18042                        "Cannot install updates to system apps on sdcard");
18043                return;
18044            } else if (instantApp) {
18045                // Abort update; system app can't be replaced with an instant app
18046                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18047                        "Cannot update a system app with an instant app");
18048                return;
18049            }
18050        }
18051
18052        if (args.move != null) {
18053            // We did an in-place move, so dex is ready to roll
18054            scanFlags |= SCAN_NO_DEX;
18055            scanFlags |= SCAN_MOVE;
18056
18057            synchronized (mPackages) {
18058                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18059                if (ps == null) {
18060                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18061                            "Missing settings for moved package " + pkgName);
18062                }
18063
18064                // We moved the entire application as-is, so bring over the
18065                // previously derived ABI information.
18066                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18067                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18068            }
18069
18070        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18071            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18072            scanFlags |= SCAN_NO_DEX;
18073
18074            try {
18075                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18076                    args.abiOverride : pkg.cpuAbiOverride);
18077                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18078                        true /*extractLibs*/, mAppLib32InstallDir);
18079            } catch (PackageManagerException pme) {
18080                Slog.e(TAG, "Error deriving application ABI", pme);
18081                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18082                return;
18083            }
18084
18085            // Shared libraries for the package need to be updated.
18086            synchronized (mPackages) {
18087                try {
18088                    updateSharedLibrariesLPr(pkg, null);
18089                } catch (PackageManagerException e) {
18090                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18091                }
18092            }
18093
18094            // dexopt can take some time to complete, so, for instant apps, we skip this
18095            // step during installation. Instead, we'll take extra time the first time the
18096            // instant app starts. It's preferred to do it this way to provide continuous
18097            // progress to the user instead of mysteriously blocking somewhere in the
18098            // middle of running an instant app.
18099            if (!instantApp) {
18100                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18101                // Do not run PackageDexOptimizer through the local performDexOpt
18102                // method because `pkg` may not be in `mPackages` yet.
18103                //
18104                // Also, don't fail application installs if the dexopt step fails.
18105                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18106                        null /* instructionSets */, false /* checkProfiles */,
18107                        getCompilerFilterForReason(REASON_INSTALL),
18108                        getOrCreateCompilerPackageStats(pkg),
18109                        mDexManager.isUsedByOtherApps(pkg.packageName),
18110                        true /* bootComplete */);
18111                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18112            }
18113
18114            // Notify BackgroundDexOptService that the package has been changed.
18115            // If this is an update of a package which used to fail to compile,
18116            // BDOS will remove it from its blacklist.
18117            // TODO: Layering violation
18118            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18119        }
18120
18121        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18122            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18123            return;
18124        }
18125
18126        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18127
18128        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18129                "installPackageLI")) {
18130            if (replace) {
18131                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18132                    // Static libs have a synthetic package name containing the version
18133                    // and cannot be updated as an update would get a new package name,
18134                    // unless this is the exact same version code which is useful for
18135                    // development.
18136                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18137                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18138                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18139                                + "static-shared libs cannot be updated");
18140                        return;
18141                    }
18142                }
18143                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18144                        installerPackageName, res, args.installReason);
18145            } else {
18146                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18147                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18148            }
18149        }
18150
18151        synchronized (mPackages) {
18152            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18153            if (ps != null) {
18154                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18155                ps.setUpdateAvailable(false /*updateAvailable*/);
18156            }
18157
18158            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18159            for (int i = 0; i < childCount; i++) {
18160                PackageParser.Package childPkg = pkg.childPackages.get(i);
18161                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18162                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18163                if (childPs != null) {
18164                    childRes.newUsers = childPs.queryInstalledUsers(
18165                            sUserManager.getUserIds(), true);
18166                }
18167            }
18168
18169            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18170                updateSequenceNumberLP(pkgName, res.newUsers);
18171                updateInstantAppInstallerLocked(pkgName);
18172            }
18173        }
18174    }
18175
18176    private void startIntentFilterVerifications(int userId, boolean replacing,
18177            PackageParser.Package pkg) {
18178        if (mIntentFilterVerifierComponent == null) {
18179            Slog.w(TAG, "No IntentFilter verification will not be done as "
18180                    + "there is no IntentFilterVerifier available!");
18181            return;
18182        }
18183
18184        final int verifierUid = getPackageUid(
18185                mIntentFilterVerifierComponent.getPackageName(),
18186                MATCH_DEBUG_TRIAGED_MISSING,
18187                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18188
18189        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18190        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18191        mHandler.sendMessage(msg);
18192
18193        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18194        for (int i = 0; i < childCount; i++) {
18195            PackageParser.Package childPkg = pkg.childPackages.get(i);
18196            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18197            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18198            mHandler.sendMessage(msg);
18199        }
18200    }
18201
18202    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18203            PackageParser.Package pkg) {
18204        int size = pkg.activities.size();
18205        if (size == 0) {
18206            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18207                    "No activity, so no need to verify any IntentFilter!");
18208            return;
18209        }
18210
18211        final boolean hasDomainURLs = hasDomainURLs(pkg);
18212        if (!hasDomainURLs) {
18213            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18214                    "No domain URLs, so no need to verify any IntentFilter!");
18215            return;
18216        }
18217
18218        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18219                + " if any IntentFilter from the " + size
18220                + " Activities needs verification ...");
18221
18222        int count = 0;
18223        final String packageName = pkg.packageName;
18224
18225        synchronized (mPackages) {
18226            // If this is a new install and we see that we've already run verification for this
18227            // package, we have nothing to do: it means the state was restored from backup.
18228            if (!replacing) {
18229                IntentFilterVerificationInfo ivi =
18230                        mSettings.getIntentFilterVerificationLPr(packageName);
18231                if (ivi != null) {
18232                    if (DEBUG_DOMAIN_VERIFICATION) {
18233                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18234                                + ivi.getStatusString());
18235                    }
18236                    return;
18237                }
18238            }
18239
18240            // If any filters need to be verified, then all need to be.
18241            boolean needToVerify = false;
18242            for (PackageParser.Activity a : pkg.activities) {
18243                for (ActivityIntentInfo filter : a.intents) {
18244                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18245                        if (DEBUG_DOMAIN_VERIFICATION) {
18246                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18247                        }
18248                        needToVerify = true;
18249                        break;
18250                    }
18251                }
18252            }
18253
18254            if (needToVerify) {
18255                final int verificationId = mIntentFilterVerificationToken++;
18256                for (PackageParser.Activity a : pkg.activities) {
18257                    for (ActivityIntentInfo filter : a.intents) {
18258                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18259                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18260                                    "Verification needed for IntentFilter:" + filter.toString());
18261                            mIntentFilterVerifier.addOneIntentFilterVerification(
18262                                    verifierUid, userId, verificationId, filter, packageName);
18263                            count++;
18264                        }
18265                    }
18266                }
18267            }
18268        }
18269
18270        if (count > 0) {
18271            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18272                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18273                    +  " for userId:" + userId);
18274            mIntentFilterVerifier.startVerifications(userId);
18275        } else {
18276            if (DEBUG_DOMAIN_VERIFICATION) {
18277                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18278            }
18279        }
18280    }
18281
18282    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18283        final ComponentName cn  = filter.activity.getComponentName();
18284        final String packageName = cn.getPackageName();
18285
18286        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18287                packageName);
18288        if (ivi == null) {
18289            return true;
18290        }
18291        int status = ivi.getStatus();
18292        switch (status) {
18293            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18294            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18295                return true;
18296
18297            default:
18298                // Nothing to do
18299                return false;
18300        }
18301    }
18302
18303    private static boolean isMultiArch(ApplicationInfo info) {
18304        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18305    }
18306
18307    private static boolean isExternal(PackageParser.Package pkg) {
18308        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18309    }
18310
18311    private static boolean isExternal(PackageSetting ps) {
18312        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18313    }
18314
18315    private static boolean isSystemApp(PackageParser.Package pkg) {
18316        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18317    }
18318
18319    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18320        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18321    }
18322
18323    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18324        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18325    }
18326
18327    private static boolean isSystemApp(PackageSetting ps) {
18328        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18329    }
18330
18331    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18332        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18333    }
18334
18335    private int packageFlagsToInstallFlags(PackageSetting ps) {
18336        int installFlags = 0;
18337        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18338            // This existing package was an external ASEC install when we have
18339            // the external flag without a UUID
18340            installFlags |= PackageManager.INSTALL_EXTERNAL;
18341        }
18342        if (ps.isForwardLocked()) {
18343            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18344        }
18345        return installFlags;
18346    }
18347
18348    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18349        if (isExternal(pkg)) {
18350            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18351                return StorageManager.UUID_PRIMARY_PHYSICAL;
18352            } else {
18353                return pkg.volumeUuid;
18354            }
18355        } else {
18356            return StorageManager.UUID_PRIVATE_INTERNAL;
18357        }
18358    }
18359
18360    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18361        if (isExternal(pkg)) {
18362            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18363                return mSettings.getExternalVersion();
18364            } else {
18365                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18366            }
18367        } else {
18368            return mSettings.getInternalVersion();
18369        }
18370    }
18371
18372    private void deleteTempPackageFiles() {
18373        final FilenameFilter filter = new FilenameFilter() {
18374            public boolean accept(File dir, String name) {
18375                return name.startsWith("vmdl") && name.endsWith(".tmp");
18376            }
18377        };
18378        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18379            file.delete();
18380        }
18381    }
18382
18383    @Override
18384    public void deletePackageAsUser(String packageName, int versionCode,
18385            IPackageDeleteObserver observer, int userId, int flags) {
18386        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18387                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18388    }
18389
18390    @Override
18391    public void deletePackageVersioned(VersionedPackage versionedPackage,
18392            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18393        final int callingUid = Binder.getCallingUid();
18394        mContext.enforceCallingOrSelfPermission(
18395                android.Manifest.permission.DELETE_PACKAGES, null);
18396        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18397                android.Manifest.permission.ACCESS_INSTANT_APPS);
18398        Preconditions.checkNotNull(versionedPackage);
18399        Preconditions.checkNotNull(observer);
18400        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18401                PackageManager.VERSION_CODE_HIGHEST,
18402                Integer.MAX_VALUE, "versionCode must be >= -1");
18403
18404        final String packageName = versionedPackage.getPackageName();
18405        final int versionCode = versionedPackage.getVersionCode();
18406        final String internalPackageName;
18407        synchronized (mPackages) {
18408            // Normalize package name to handle renamed packages and static libs
18409            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18410                    versionedPackage.getVersionCode());
18411        }
18412
18413        final int uid = Binder.getCallingUid();
18414        if (!isOrphaned(internalPackageName)
18415                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18416            try {
18417                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18418                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18419                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18420                observer.onUserActionRequired(intent);
18421            } catch (RemoteException re) {
18422            }
18423            return;
18424        }
18425        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18426        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18427        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18428            mContext.enforceCallingOrSelfPermission(
18429                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18430                    "deletePackage for user " + userId);
18431        }
18432
18433        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18434            try {
18435                observer.onPackageDeleted(packageName,
18436                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18437            } catch (RemoteException re) {
18438            }
18439            return;
18440        }
18441
18442        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18443            try {
18444                observer.onPackageDeleted(packageName,
18445                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18446            } catch (RemoteException re) {
18447            }
18448            return;
18449        }
18450
18451        if (DEBUG_REMOVE) {
18452            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18453                    + " deleteAllUsers: " + deleteAllUsers + " version="
18454                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18455                    ? "VERSION_CODE_HIGHEST" : versionCode));
18456        }
18457        // Queue up an async operation since the package deletion may take a little while.
18458        mHandler.post(new Runnable() {
18459            public void run() {
18460                mHandler.removeCallbacks(this);
18461                int returnCode;
18462                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18463                boolean doDeletePackage = true;
18464                if (ps != null) {
18465                    final boolean targetIsInstantApp =
18466                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18467                    doDeletePackage = !targetIsInstantApp
18468                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18469                }
18470                if (doDeletePackage) {
18471                    if (!deleteAllUsers) {
18472                        returnCode = deletePackageX(internalPackageName, versionCode,
18473                                userId, deleteFlags);
18474                    } else {
18475                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18476                                internalPackageName, users);
18477                        // If nobody is blocking uninstall, proceed with delete for all users
18478                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18479                            returnCode = deletePackageX(internalPackageName, versionCode,
18480                                    userId, deleteFlags);
18481                        } else {
18482                            // Otherwise uninstall individually for users with blockUninstalls=false
18483                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18484                            for (int userId : users) {
18485                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18486                                    returnCode = deletePackageX(internalPackageName, versionCode,
18487                                            userId, userFlags);
18488                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18489                                        Slog.w(TAG, "Package delete failed for user " + userId
18490                                                + ", returnCode " + returnCode);
18491                                    }
18492                                }
18493                            }
18494                            // The app has only been marked uninstalled for certain users.
18495                            // We still need to report that delete was blocked
18496                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18497                        }
18498                    }
18499                } else {
18500                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18501                }
18502                try {
18503                    observer.onPackageDeleted(packageName, returnCode, null);
18504                } catch (RemoteException e) {
18505                    Log.i(TAG, "Observer no longer exists.");
18506                } //end catch
18507            } //end run
18508        });
18509    }
18510
18511    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18512        if (pkg.staticSharedLibName != null) {
18513            return pkg.manifestPackageName;
18514        }
18515        return pkg.packageName;
18516    }
18517
18518    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18519        // Handle renamed packages
18520        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18521        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18522
18523        // Is this a static library?
18524        SparseArray<SharedLibraryEntry> versionedLib =
18525                mStaticLibsByDeclaringPackage.get(packageName);
18526        if (versionedLib == null || versionedLib.size() <= 0) {
18527            return packageName;
18528        }
18529
18530        // Figure out which lib versions the caller can see
18531        SparseIntArray versionsCallerCanSee = null;
18532        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18533        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18534                && callingAppId != Process.ROOT_UID) {
18535            versionsCallerCanSee = new SparseIntArray();
18536            String libName = versionedLib.valueAt(0).info.getName();
18537            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18538            if (uidPackages != null) {
18539                for (String uidPackage : uidPackages) {
18540                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18541                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18542                    if (libIdx >= 0) {
18543                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18544                        versionsCallerCanSee.append(libVersion, libVersion);
18545                    }
18546                }
18547            }
18548        }
18549
18550        // Caller can see nothing - done
18551        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18552            return packageName;
18553        }
18554
18555        // Find the version the caller can see and the app version code
18556        SharedLibraryEntry highestVersion = null;
18557        final int versionCount = versionedLib.size();
18558        for (int i = 0; i < versionCount; i++) {
18559            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18560            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18561                    libEntry.info.getVersion()) < 0) {
18562                continue;
18563            }
18564            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18565            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18566                if (libVersionCode == versionCode) {
18567                    return libEntry.apk;
18568                }
18569            } else if (highestVersion == null) {
18570                highestVersion = libEntry;
18571            } else if (libVersionCode  > highestVersion.info
18572                    .getDeclaringPackage().getVersionCode()) {
18573                highestVersion = libEntry;
18574            }
18575        }
18576
18577        if (highestVersion != null) {
18578            return highestVersion.apk;
18579        }
18580
18581        return packageName;
18582    }
18583
18584    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18585        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18586              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18587            return true;
18588        }
18589        final int callingUserId = UserHandle.getUserId(callingUid);
18590        // If the caller installed the pkgName, then allow it to silently uninstall.
18591        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18592            return true;
18593        }
18594
18595        // Allow package verifier to silently uninstall.
18596        if (mRequiredVerifierPackage != null &&
18597                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18598            return true;
18599        }
18600
18601        // Allow package uninstaller to silently uninstall.
18602        if (mRequiredUninstallerPackage != null &&
18603                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18604            return true;
18605        }
18606
18607        // Allow storage manager to silently uninstall.
18608        if (mStorageManagerPackage != null &&
18609                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18610            return true;
18611        }
18612
18613        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18614        // uninstall for device owner provisioning.
18615        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18616                == PERMISSION_GRANTED) {
18617            return true;
18618        }
18619
18620        return false;
18621    }
18622
18623    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18624        int[] result = EMPTY_INT_ARRAY;
18625        for (int userId : userIds) {
18626            if (getBlockUninstallForUser(packageName, userId)) {
18627                result = ArrayUtils.appendInt(result, userId);
18628            }
18629        }
18630        return result;
18631    }
18632
18633    @Override
18634    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18635        final int callingUid = Binder.getCallingUid();
18636        if (getInstantAppPackageName(callingUid) != null
18637                && !isCallerSameApp(packageName, callingUid)) {
18638            return false;
18639        }
18640        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18641    }
18642
18643    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18644        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18645                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18646        try {
18647            if (dpm != null) {
18648                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18649                        /* callingUserOnly =*/ false);
18650                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18651                        : deviceOwnerComponentName.getPackageName();
18652                // Does the package contains the device owner?
18653                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18654                // this check is probably not needed, since DO should be registered as a device
18655                // admin on some user too. (Original bug for this: b/17657954)
18656                if (packageName.equals(deviceOwnerPackageName)) {
18657                    return true;
18658                }
18659                // Does it contain a device admin for any user?
18660                int[] users;
18661                if (userId == UserHandle.USER_ALL) {
18662                    users = sUserManager.getUserIds();
18663                } else {
18664                    users = new int[]{userId};
18665                }
18666                for (int i = 0; i < users.length; ++i) {
18667                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18668                        return true;
18669                    }
18670                }
18671            }
18672        } catch (RemoteException e) {
18673        }
18674        return false;
18675    }
18676
18677    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18678        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18679    }
18680
18681    /**
18682     *  This method is an internal method that could be get invoked either
18683     *  to delete an installed package or to clean up a failed installation.
18684     *  After deleting an installed package, a broadcast is sent to notify any
18685     *  listeners that the package has been removed. For cleaning up a failed
18686     *  installation, the broadcast is not necessary since the package's
18687     *  installation wouldn't have sent the initial broadcast either
18688     *  The key steps in deleting a package are
18689     *  deleting the package information in internal structures like mPackages,
18690     *  deleting the packages base directories through installd
18691     *  updating mSettings to reflect current status
18692     *  persisting settings for later use
18693     *  sending a broadcast if necessary
18694     */
18695    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18696        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18697        final boolean res;
18698
18699        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18700                ? UserHandle.USER_ALL : userId;
18701
18702        if (isPackageDeviceAdmin(packageName, removeUser)) {
18703            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18704            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18705        }
18706
18707        PackageSetting uninstalledPs = null;
18708        PackageParser.Package pkg = null;
18709
18710        // for the uninstall-updates case and restricted profiles, remember the per-
18711        // user handle installed state
18712        int[] allUsers;
18713        synchronized (mPackages) {
18714            uninstalledPs = mSettings.mPackages.get(packageName);
18715            if (uninstalledPs == null) {
18716                Slog.w(TAG, "Not removing non-existent package " + packageName);
18717                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18718            }
18719
18720            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18721                    && uninstalledPs.versionCode != versionCode) {
18722                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18723                        + uninstalledPs.versionCode + " != " + versionCode);
18724                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18725            }
18726
18727            // Static shared libs can be declared by any package, so let us not
18728            // allow removing a package if it provides a lib others depend on.
18729            pkg = mPackages.get(packageName);
18730
18731            allUsers = sUserManager.getUserIds();
18732
18733            if (pkg != null && pkg.staticSharedLibName != null) {
18734                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18735                        pkg.staticSharedLibVersion);
18736                if (libEntry != null) {
18737                    for (int currUserId : allUsers) {
18738                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18739                            continue;
18740                        }
18741                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18742                                libEntry.info, 0, currUserId);
18743                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18744                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18745                                    + " hosting lib " + libEntry.info.getName() + " version "
18746                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18747                                    + " for user " + currUserId);
18748                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18749                        }
18750                    }
18751                }
18752            }
18753
18754            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18755        }
18756
18757        final int freezeUser;
18758        if (isUpdatedSystemApp(uninstalledPs)
18759                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18760            // We're downgrading a system app, which will apply to all users, so
18761            // freeze them all during the downgrade
18762            freezeUser = UserHandle.USER_ALL;
18763        } else {
18764            freezeUser = removeUser;
18765        }
18766
18767        synchronized (mInstallLock) {
18768            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18769            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18770                    deleteFlags, "deletePackageX")) {
18771                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18772                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18773            }
18774            synchronized (mPackages) {
18775                if (res) {
18776                    if (pkg != null) {
18777                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18778                    }
18779                    updateSequenceNumberLP(packageName, info.removedUsers);
18780                    updateInstantAppInstallerLocked(packageName);
18781                }
18782            }
18783        }
18784
18785        if (res) {
18786            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18787            info.sendPackageRemovedBroadcasts(killApp);
18788            info.sendSystemPackageUpdatedBroadcasts();
18789            info.sendSystemPackageAppearedBroadcasts();
18790        }
18791        // Force a gc here.
18792        Runtime.getRuntime().gc();
18793        // Delete the resources here after sending the broadcast to let
18794        // other processes clean up before deleting resources.
18795        if (info.args != null) {
18796            synchronized (mInstallLock) {
18797                info.args.doPostDeleteLI(true);
18798            }
18799        }
18800
18801        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18802    }
18803
18804    static class PackageRemovedInfo {
18805        final PackageSender packageSender;
18806        String removedPackage;
18807        String installerPackageName;
18808        int uid = -1;
18809        int removedAppId = -1;
18810        int[] origUsers;
18811        int[] removedUsers = null;
18812        int[] broadcastUsers = null;
18813        SparseArray<Integer> installReasons;
18814        boolean isRemovedPackageSystemUpdate = false;
18815        boolean isUpdate;
18816        boolean dataRemoved;
18817        boolean removedForAllUsers;
18818        boolean isStaticSharedLib;
18819        // Clean up resources deleted packages.
18820        InstallArgs args = null;
18821        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18822        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18823
18824        PackageRemovedInfo(PackageSender packageSender) {
18825            this.packageSender = packageSender;
18826        }
18827
18828        void sendPackageRemovedBroadcasts(boolean killApp) {
18829            sendPackageRemovedBroadcastInternal(killApp);
18830            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18831            for (int i = 0; i < childCount; i++) {
18832                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18833                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18834            }
18835        }
18836
18837        void sendSystemPackageUpdatedBroadcasts() {
18838            if (isRemovedPackageSystemUpdate) {
18839                sendSystemPackageUpdatedBroadcastsInternal();
18840                final int childCount = (removedChildPackages != null)
18841                        ? removedChildPackages.size() : 0;
18842                for (int i = 0; i < childCount; i++) {
18843                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18844                    if (childInfo.isRemovedPackageSystemUpdate) {
18845                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18846                    }
18847                }
18848            }
18849        }
18850
18851        void sendSystemPackageAppearedBroadcasts() {
18852            final int packageCount = (appearedChildPackages != null)
18853                    ? appearedChildPackages.size() : 0;
18854            for (int i = 0; i < packageCount; i++) {
18855                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18856                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18857                    true, UserHandle.getAppId(installedInfo.uid),
18858                    installedInfo.newUsers);
18859            }
18860        }
18861
18862        private void sendSystemPackageUpdatedBroadcastsInternal() {
18863            Bundle extras = new Bundle(2);
18864            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18865            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18866            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18867                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18868            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18869                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18870            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18871                null, null, 0, removedPackage, null, null);
18872            if (installerPackageName != null) {
18873                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18874                        removedPackage, extras, 0 /*flags*/,
18875                        installerPackageName, null, null);
18876                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18877                        removedPackage, extras, 0 /*flags*/,
18878                        installerPackageName, null, null);
18879            }
18880        }
18881
18882        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18883            // Don't send static shared library removal broadcasts as these
18884            // libs are visible only the the apps that depend on them an one
18885            // cannot remove the library if it has a dependency.
18886            if (isStaticSharedLib) {
18887                return;
18888            }
18889            Bundle extras = new Bundle(2);
18890            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18891            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18892            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18893            if (isUpdate || isRemovedPackageSystemUpdate) {
18894                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18895            }
18896            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18897            if (removedPackage != null) {
18898                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18899                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18900                if (installerPackageName != null) {
18901                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18902                            removedPackage, extras, 0 /*flags*/,
18903                            installerPackageName, null, broadcastUsers);
18904                }
18905                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18906                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18907                        removedPackage, extras,
18908                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18909                        null, null, broadcastUsers);
18910                }
18911            }
18912            if (removedAppId >= 0) {
18913                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18914                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18915            }
18916        }
18917
18918        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18919            removedUsers = userIds;
18920            if (removedUsers == null) {
18921                broadcastUsers = null;
18922                return;
18923            }
18924
18925            broadcastUsers = EMPTY_INT_ARRAY;
18926            for (int i = userIds.length - 1; i >= 0; --i) {
18927                final int userId = userIds[i];
18928                if (deletedPackageSetting.getInstantApp(userId)) {
18929                    continue;
18930                }
18931                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18932            }
18933        }
18934    }
18935
18936    /*
18937     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18938     * flag is not set, the data directory is removed as well.
18939     * make sure this flag is set for partially installed apps. If not its meaningless to
18940     * delete a partially installed application.
18941     */
18942    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18943            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18944        String packageName = ps.name;
18945        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18946        // Retrieve object to delete permissions for shared user later on
18947        final PackageParser.Package deletedPkg;
18948        final PackageSetting deletedPs;
18949        // reader
18950        synchronized (mPackages) {
18951            deletedPkg = mPackages.get(packageName);
18952            deletedPs = mSettings.mPackages.get(packageName);
18953            if (outInfo != null) {
18954                outInfo.removedPackage = packageName;
18955                outInfo.installerPackageName = ps.installerPackageName;
18956                outInfo.isStaticSharedLib = deletedPkg != null
18957                        && deletedPkg.staticSharedLibName != null;
18958                outInfo.populateUsers(deletedPs == null ? null
18959                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18960            }
18961        }
18962
18963        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18964
18965        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18966            final PackageParser.Package resolvedPkg;
18967            if (deletedPkg != null) {
18968                resolvedPkg = deletedPkg;
18969            } else {
18970                // We don't have a parsed package when it lives on an ejected
18971                // adopted storage device, so fake something together
18972                resolvedPkg = new PackageParser.Package(ps.name);
18973                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18974            }
18975            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18976                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18977            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18978            if (outInfo != null) {
18979                outInfo.dataRemoved = true;
18980            }
18981            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18982        }
18983
18984        int removedAppId = -1;
18985
18986        // writer
18987        synchronized (mPackages) {
18988            boolean installedStateChanged = false;
18989            if (deletedPs != null) {
18990                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18991                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18992                    clearDefaultBrowserIfNeeded(packageName);
18993                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18994                    removedAppId = mSettings.removePackageLPw(packageName);
18995                    if (outInfo != null) {
18996                        outInfo.removedAppId = removedAppId;
18997                    }
18998                    updatePermissionsLPw(deletedPs.name, null, 0);
18999                    if (deletedPs.sharedUser != null) {
19000                        // Remove permissions associated with package. Since runtime
19001                        // permissions are per user we have to kill the removed package
19002                        // or packages running under the shared user of the removed
19003                        // package if revoking the permissions requested only by the removed
19004                        // package is successful and this causes a change in gids.
19005                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19006                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19007                                    userId);
19008                            if (userIdToKill == UserHandle.USER_ALL
19009                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19010                                // If gids changed for this user, kill all affected packages.
19011                                mHandler.post(new Runnable() {
19012                                    @Override
19013                                    public void run() {
19014                                        // This has to happen with no lock held.
19015                                        killApplication(deletedPs.name, deletedPs.appId,
19016                                                KILL_APP_REASON_GIDS_CHANGED);
19017                                    }
19018                                });
19019                                break;
19020                            }
19021                        }
19022                    }
19023                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19024                }
19025                // make sure to preserve per-user disabled state if this removal was just
19026                // a downgrade of a system app to the factory package
19027                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19028                    if (DEBUG_REMOVE) {
19029                        Slog.d(TAG, "Propagating install state across downgrade");
19030                    }
19031                    for (int userId : allUserHandles) {
19032                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19033                        if (DEBUG_REMOVE) {
19034                            Slog.d(TAG, "    user " + userId + " => " + installed);
19035                        }
19036                        if (installed != ps.getInstalled(userId)) {
19037                            installedStateChanged = true;
19038                        }
19039                        ps.setInstalled(installed, userId);
19040                    }
19041                }
19042            }
19043            // can downgrade to reader
19044            if (writeSettings) {
19045                // Save settings now
19046                mSettings.writeLPr();
19047            }
19048            if (installedStateChanged) {
19049                mSettings.writeKernelMappingLPr(ps);
19050            }
19051        }
19052        if (removedAppId != -1) {
19053            // A user ID was deleted here. Go through all users and remove it
19054            // from KeyStore.
19055            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19056        }
19057    }
19058
19059    static boolean locationIsPrivileged(File path) {
19060        try {
19061            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19062                    .getCanonicalPath();
19063            return path.getCanonicalPath().startsWith(privilegedAppDir);
19064        } catch (IOException e) {
19065            Slog.e(TAG, "Unable to access code path " + path);
19066        }
19067        return false;
19068    }
19069
19070    /*
19071     * Tries to delete system package.
19072     */
19073    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19074            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19075            boolean writeSettings) {
19076        if (deletedPs.parentPackageName != null) {
19077            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19078            return false;
19079        }
19080
19081        final boolean applyUserRestrictions
19082                = (allUserHandles != null) && (outInfo.origUsers != null);
19083        final PackageSetting disabledPs;
19084        // Confirm if the system package has been updated
19085        // An updated system app can be deleted. This will also have to restore
19086        // the system pkg from system partition
19087        // reader
19088        synchronized (mPackages) {
19089            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19090        }
19091
19092        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19093                + " disabledPs=" + disabledPs);
19094
19095        if (disabledPs == null) {
19096            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19097            return false;
19098        } else if (DEBUG_REMOVE) {
19099            Slog.d(TAG, "Deleting system pkg from data partition");
19100        }
19101
19102        if (DEBUG_REMOVE) {
19103            if (applyUserRestrictions) {
19104                Slog.d(TAG, "Remembering install states:");
19105                for (int userId : allUserHandles) {
19106                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19107                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19108                }
19109            }
19110        }
19111
19112        // Delete the updated package
19113        outInfo.isRemovedPackageSystemUpdate = true;
19114        if (outInfo.removedChildPackages != null) {
19115            final int childCount = (deletedPs.childPackageNames != null)
19116                    ? deletedPs.childPackageNames.size() : 0;
19117            for (int i = 0; i < childCount; i++) {
19118                String childPackageName = deletedPs.childPackageNames.get(i);
19119                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19120                        .contains(childPackageName)) {
19121                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19122                            childPackageName);
19123                    if (childInfo != null) {
19124                        childInfo.isRemovedPackageSystemUpdate = true;
19125                    }
19126                }
19127            }
19128        }
19129
19130        if (disabledPs.versionCode < deletedPs.versionCode) {
19131            // Delete data for downgrades
19132            flags &= ~PackageManager.DELETE_KEEP_DATA;
19133        } else {
19134            // Preserve data by setting flag
19135            flags |= PackageManager.DELETE_KEEP_DATA;
19136        }
19137
19138        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19139                outInfo, writeSettings, disabledPs.pkg);
19140        if (!ret) {
19141            return false;
19142        }
19143
19144        // writer
19145        synchronized (mPackages) {
19146            // Reinstate the old system package
19147            enableSystemPackageLPw(disabledPs.pkg);
19148            // Remove any native libraries from the upgraded package.
19149            removeNativeBinariesLI(deletedPs);
19150        }
19151
19152        // Install the system package
19153        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19154        int parseFlags = mDefParseFlags
19155                | PackageParser.PARSE_MUST_BE_APK
19156                | PackageParser.PARSE_IS_SYSTEM
19157                | PackageParser.PARSE_IS_SYSTEM_DIR;
19158        if (locationIsPrivileged(disabledPs.codePath)) {
19159            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19160        }
19161
19162        final PackageParser.Package newPkg;
19163        try {
19164            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19165                0 /* currentTime */, null);
19166        } catch (PackageManagerException e) {
19167            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19168                    + e.getMessage());
19169            return false;
19170        }
19171
19172        try {
19173            // update shared libraries for the newly re-installed system package
19174            updateSharedLibrariesLPr(newPkg, null);
19175        } catch (PackageManagerException e) {
19176            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19177        }
19178
19179        prepareAppDataAfterInstallLIF(newPkg);
19180
19181        // writer
19182        synchronized (mPackages) {
19183            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19184
19185            // Propagate the permissions state as we do not want to drop on the floor
19186            // runtime permissions. The update permissions method below will take
19187            // care of removing obsolete permissions and grant install permissions.
19188            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19189            updatePermissionsLPw(newPkg.packageName, newPkg,
19190                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19191
19192            if (applyUserRestrictions) {
19193                boolean installedStateChanged = false;
19194                if (DEBUG_REMOVE) {
19195                    Slog.d(TAG, "Propagating install state across reinstall");
19196                }
19197                for (int userId : allUserHandles) {
19198                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19199                    if (DEBUG_REMOVE) {
19200                        Slog.d(TAG, "    user " + userId + " => " + installed);
19201                    }
19202                    if (installed != ps.getInstalled(userId)) {
19203                        installedStateChanged = true;
19204                    }
19205                    ps.setInstalled(installed, userId);
19206
19207                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19208                }
19209                // Regardless of writeSettings we need to ensure that this restriction
19210                // state propagation is persisted
19211                mSettings.writeAllUsersPackageRestrictionsLPr();
19212                if (installedStateChanged) {
19213                    mSettings.writeKernelMappingLPr(ps);
19214                }
19215            }
19216            // can downgrade to reader here
19217            if (writeSettings) {
19218                mSettings.writeLPr();
19219            }
19220        }
19221        return true;
19222    }
19223
19224    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19225            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19226            PackageRemovedInfo outInfo, boolean writeSettings,
19227            PackageParser.Package replacingPackage) {
19228        synchronized (mPackages) {
19229            if (outInfo != null) {
19230                outInfo.uid = ps.appId;
19231            }
19232
19233            if (outInfo != null && outInfo.removedChildPackages != null) {
19234                final int childCount = (ps.childPackageNames != null)
19235                        ? ps.childPackageNames.size() : 0;
19236                for (int i = 0; i < childCount; i++) {
19237                    String childPackageName = ps.childPackageNames.get(i);
19238                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19239                    if (childPs == null) {
19240                        return false;
19241                    }
19242                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19243                            childPackageName);
19244                    if (childInfo != null) {
19245                        childInfo.uid = childPs.appId;
19246                    }
19247                }
19248            }
19249        }
19250
19251        // Delete package data from internal structures and also remove data if flag is set
19252        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19253
19254        // Delete the child packages data
19255        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19256        for (int i = 0; i < childCount; i++) {
19257            PackageSetting childPs;
19258            synchronized (mPackages) {
19259                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19260            }
19261            if (childPs != null) {
19262                PackageRemovedInfo childOutInfo = (outInfo != null
19263                        && outInfo.removedChildPackages != null)
19264                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19265                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19266                        && (replacingPackage != null
19267                        && !replacingPackage.hasChildPackage(childPs.name))
19268                        ? flags & ~DELETE_KEEP_DATA : flags;
19269                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19270                        deleteFlags, writeSettings);
19271            }
19272        }
19273
19274        // Delete application code and resources only for parent packages
19275        if (ps.parentPackageName == null) {
19276            if (deleteCodeAndResources && (outInfo != null)) {
19277                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19278                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19279                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19280            }
19281        }
19282
19283        return true;
19284    }
19285
19286    @Override
19287    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19288            int userId) {
19289        mContext.enforceCallingOrSelfPermission(
19290                android.Manifest.permission.DELETE_PACKAGES, null);
19291        synchronized (mPackages) {
19292            // Cannot block uninstall of static shared libs as they are
19293            // considered a part of the using app (emulating static linking).
19294            // Also static libs are installed always on internal storage.
19295            PackageParser.Package pkg = mPackages.get(packageName);
19296            if (pkg != null && pkg.staticSharedLibName != null) {
19297                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19298                        + " providing static shared library: " + pkg.staticSharedLibName);
19299                return false;
19300            }
19301            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19302            mSettings.writePackageRestrictionsLPr(userId);
19303        }
19304        return true;
19305    }
19306
19307    @Override
19308    public boolean getBlockUninstallForUser(String packageName, int userId) {
19309        synchronized (mPackages) {
19310            final PackageSetting ps = mSettings.mPackages.get(packageName);
19311            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19312                return true;
19313            }
19314            return mSettings.getBlockUninstallLPr(userId, packageName);
19315        }
19316    }
19317
19318    @Override
19319    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19320        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19321        synchronized (mPackages) {
19322            PackageSetting ps = mSettings.mPackages.get(packageName);
19323            if (ps == null) {
19324                Log.w(TAG, "Package doesn't exist: " + packageName);
19325                return false;
19326            }
19327            if (systemUserApp) {
19328                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19329            } else {
19330                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19331            }
19332            mSettings.writeLPr();
19333        }
19334        return true;
19335    }
19336
19337    /*
19338     * This method handles package deletion in general
19339     */
19340    private boolean deletePackageLIF(String packageName, UserHandle user,
19341            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19342            PackageRemovedInfo outInfo, boolean writeSettings,
19343            PackageParser.Package replacingPackage) {
19344        if (packageName == null) {
19345            Slog.w(TAG, "Attempt to delete null packageName.");
19346            return false;
19347        }
19348
19349        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19350
19351        PackageSetting ps;
19352        synchronized (mPackages) {
19353            ps = mSettings.mPackages.get(packageName);
19354            if (ps == null) {
19355                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19356                return false;
19357            }
19358
19359            if (ps.parentPackageName != null && (!isSystemApp(ps)
19360                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19361                if (DEBUG_REMOVE) {
19362                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19363                            + ((user == null) ? UserHandle.USER_ALL : user));
19364                }
19365                final int removedUserId = (user != null) ? user.getIdentifier()
19366                        : UserHandle.USER_ALL;
19367                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19368                    return false;
19369                }
19370                markPackageUninstalledForUserLPw(ps, user);
19371                scheduleWritePackageRestrictionsLocked(user);
19372                return true;
19373            }
19374        }
19375
19376        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19377                && user.getIdentifier() != UserHandle.USER_ALL)) {
19378            // The caller is asking that the package only be deleted for a single
19379            // user.  To do this, we just mark its uninstalled state and delete
19380            // its data. If this is a system app, we only allow this to happen if
19381            // they have set the special DELETE_SYSTEM_APP which requests different
19382            // semantics than normal for uninstalling system apps.
19383            markPackageUninstalledForUserLPw(ps, user);
19384
19385            if (!isSystemApp(ps)) {
19386                // Do not uninstall the APK if an app should be cached
19387                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19388                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19389                    // Other user still have this package installed, so all
19390                    // we need to do is clear this user's data and save that
19391                    // it is uninstalled.
19392                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19393                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19394                        return false;
19395                    }
19396                    scheduleWritePackageRestrictionsLocked(user);
19397                    return true;
19398                } else {
19399                    // We need to set it back to 'installed' so the uninstall
19400                    // broadcasts will be sent correctly.
19401                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19402                    ps.setInstalled(true, user.getIdentifier());
19403                    mSettings.writeKernelMappingLPr(ps);
19404                }
19405            } else {
19406                // This is a system app, so we assume that the
19407                // other users still have this package installed, so all
19408                // we need to do is clear this user's data and save that
19409                // it is uninstalled.
19410                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19411                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19412                    return false;
19413                }
19414                scheduleWritePackageRestrictionsLocked(user);
19415                return true;
19416            }
19417        }
19418
19419        // If we are deleting a composite package for all users, keep track
19420        // of result for each child.
19421        if (ps.childPackageNames != null && outInfo != null) {
19422            synchronized (mPackages) {
19423                final int childCount = ps.childPackageNames.size();
19424                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19425                for (int i = 0; i < childCount; i++) {
19426                    String childPackageName = ps.childPackageNames.get(i);
19427                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19428                    childInfo.removedPackage = childPackageName;
19429                    childInfo.installerPackageName = ps.installerPackageName;
19430                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19431                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19432                    if (childPs != null) {
19433                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19434                    }
19435                }
19436            }
19437        }
19438
19439        boolean ret = false;
19440        if (isSystemApp(ps)) {
19441            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19442            // When an updated system application is deleted we delete the existing resources
19443            // as well and fall back to existing code in system partition
19444            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19445        } else {
19446            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19447            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19448                    outInfo, writeSettings, replacingPackage);
19449        }
19450
19451        // Take a note whether we deleted the package for all users
19452        if (outInfo != null) {
19453            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19454            if (outInfo.removedChildPackages != null) {
19455                synchronized (mPackages) {
19456                    final int childCount = outInfo.removedChildPackages.size();
19457                    for (int i = 0; i < childCount; i++) {
19458                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19459                        if (childInfo != null) {
19460                            childInfo.removedForAllUsers = mPackages.get(
19461                                    childInfo.removedPackage) == null;
19462                        }
19463                    }
19464                }
19465            }
19466            // If we uninstalled an update to a system app there may be some
19467            // child packages that appeared as they are declared in the system
19468            // app but were not declared in the update.
19469            if (isSystemApp(ps)) {
19470                synchronized (mPackages) {
19471                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19472                    final int childCount = (updatedPs.childPackageNames != null)
19473                            ? updatedPs.childPackageNames.size() : 0;
19474                    for (int i = 0; i < childCount; i++) {
19475                        String childPackageName = updatedPs.childPackageNames.get(i);
19476                        if (outInfo.removedChildPackages == null
19477                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19478                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19479                            if (childPs == null) {
19480                                continue;
19481                            }
19482                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19483                            installRes.name = childPackageName;
19484                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19485                            installRes.pkg = mPackages.get(childPackageName);
19486                            installRes.uid = childPs.pkg.applicationInfo.uid;
19487                            if (outInfo.appearedChildPackages == null) {
19488                                outInfo.appearedChildPackages = new ArrayMap<>();
19489                            }
19490                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19491                        }
19492                    }
19493                }
19494            }
19495        }
19496
19497        return ret;
19498    }
19499
19500    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19501        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19502                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19503        for (int nextUserId : userIds) {
19504            if (DEBUG_REMOVE) {
19505                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19506            }
19507            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19508                    false /*installed*/,
19509                    true /*stopped*/,
19510                    true /*notLaunched*/,
19511                    false /*hidden*/,
19512                    false /*suspended*/,
19513                    false /*instantApp*/,
19514                    null /*lastDisableAppCaller*/,
19515                    null /*enabledComponents*/,
19516                    null /*disabledComponents*/,
19517                    ps.readUserState(nextUserId).domainVerificationStatus,
19518                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19519        }
19520        mSettings.writeKernelMappingLPr(ps);
19521    }
19522
19523    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19524            PackageRemovedInfo outInfo) {
19525        final PackageParser.Package pkg;
19526        synchronized (mPackages) {
19527            pkg = mPackages.get(ps.name);
19528        }
19529
19530        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19531                : new int[] {userId};
19532        for (int nextUserId : userIds) {
19533            if (DEBUG_REMOVE) {
19534                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19535                        + nextUserId);
19536            }
19537
19538            destroyAppDataLIF(pkg, userId,
19539                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19540            destroyAppProfilesLIF(pkg, userId);
19541            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19542            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19543            schedulePackageCleaning(ps.name, nextUserId, false);
19544            synchronized (mPackages) {
19545                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19546                    scheduleWritePackageRestrictionsLocked(nextUserId);
19547                }
19548                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19549            }
19550        }
19551
19552        if (outInfo != null) {
19553            outInfo.removedPackage = ps.name;
19554            outInfo.installerPackageName = ps.installerPackageName;
19555            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19556            outInfo.removedAppId = ps.appId;
19557            outInfo.removedUsers = userIds;
19558            outInfo.broadcastUsers = userIds;
19559        }
19560
19561        return true;
19562    }
19563
19564    private final class ClearStorageConnection implements ServiceConnection {
19565        IMediaContainerService mContainerService;
19566
19567        @Override
19568        public void onServiceConnected(ComponentName name, IBinder service) {
19569            synchronized (this) {
19570                mContainerService = IMediaContainerService.Stub
19571                        .asInterface(Binder.allowBlocking(service));
19572                notifyAll();
19573            }
19574        }
19575
19576        @Override
19577        public void onServiceDisconnected(ComponentName name) {
19578        }
19579    }
19580
19581    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19582        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19583
19584        final boolean mounted;
19585        if (Environment.isExternalStorageEmulated()) {
19586            mounted = true;
19587        } else {
19588            final String status = Environment.getExternalStorageState();
19589
19590            mounted = status.equals(Environment.MEDIA_MOUNTED)
19591                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19592        }
19593
19594        if (!mounted) {
19595            return;
19596        }
19597
19598        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19599        int[] users;
19600        if (userId == UserHandle.USER_ALL) {
19601            users = sUserManager.getUserIds();
19602        } else {
19603            users = new int[] { userId };
19604        }
19605        final ClearStorageConnection conn = new ClearStorageConnection();
19606        if (mContext.bindServiceAsUser(
19607                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19608            try {
19609                for (int curUser : users) {
19610                    long timeout = SystemClock.uptimeMillis() + 5000;
19611                    synchronized (conn) {
19612                        long now;
19613                        while (conn.mContainerService == null &&
19614                                (now = SystemClock.uptimeMillis()) < timeout) {
19615                            try {
19616                                conn.wait(timeout - now);
19617                            } catch (InterruptedException e) {
19618                            }
19619                        }
19620                    }
19621                    if (conn.mContainerService == null) {
19622                        return;
19623                    }
19624
19625                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19626                    clearDirectory(conn.mContainerService,
19627                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19628                    if (allData) {
19629                        clearDirectory(conn.mContainerService,
19630                                userEnv.buildExternalStorageAppDataDirs(packageName));
19631                        clearDirectory(conn.mContainerService,
19632                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19633                    }
19634                }
19635            } finally {
19636                mContext.unbindService(conn);
19637            }
19638        }
19639    }
19640
19641    @Override
19642    public void clearApplicationProfileData(String packageName) {
19643        enforceSystemOrRoot("Only the system can clear all profile data");
19644
19645        final PackageParser.Package pkg;
19646        synchronized (mPackages) {
19647            pkg = mPackages.get(packageName);
19648        }
19649
19650        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19651            synchronized (mInstallLock) {
19652                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19653            }
19654        }
19655    }
19656
19657    @Override
19658    public void clearApplicationUserData(final String packageName,
19659            final IPackageDataObserver observer, final int userId) {
19660        mContext.enforceCallingOrSelfPermission(
19661                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19662
19663        final int callingUid = Binder.getCallingUid();
19664        enforceCrossUserPermission(callingUid, userId,
19665                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19666
19667        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19668        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19669            return;
19670        }
19671        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19672            throw new SecurityException("Cannot clear data for a protected package: "
19673                    + packageName);
19674        }
19675        // Queue up an async operation since the package deletion may take a little while.
19676        mHandler.post(new Runnable() {
19677            public void run() {
19678                mHandler.removeCallbacks(this);
19679                final boolean succeeded;
19680                try (PackageFreezer freezer = freezePackage(packageName,
19681                        "clearApplicationUserData")) {
19682                    synchronized (mInstallLock) {
19683                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19684                    }
19685                    clearExternalStorageDataSync(packageName, userId, true);
19686                    synchronized (mPackages) {
19687                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19688                                packageName, userId);
19689                    }
19690                }
19691                if (succeeded) {
19692                    // invoke DeviceStorageMonitor's update method to clear any notifications
19693                    DeviceStorageMonitorInternal dsm = LocalServices
19694                            .getService(DeviceStorageMonitorInternal.class);
19695                    if (dsm != null) {
19696                        dsm.checkMemory();
19697                    }
19698                }
19699                if(observer != null) {
19700                    try {
19701                        observer.onRemoveCompleted(packageName, succeeded);
19702                    } catch (RemoteException e) {
19703                        Log.i(TAG, "Observer no longer exists.");
19704                    }
19705                } //end if observer
19706            } //end run
19707        });
19708    }
19709
19710    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19711        if (packageName == null) {
19712            Slog.w(TAG, "Attempt to delete null packageName.");
19713            return false;
19714        }
19715
19716        // Try finding details about the requested package
19717        PackageParser.Package pkg;
19718        synchronized (mPackages) {
19719            pkg = mPackages.get(packageName);
19720            if (pkg == null) {
19721                final PackageSetting ps = mSettings.mPackages.get(packageName);
19722                if (ps != null) {
19723                    pkg = ps.pkg;
19724                }
19725            }
19726
19727            if (pkg == null) {
19728                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19729                return false;
19730            }
19731
19732            PackageSetting ps = (PackageSetting) pkg.mExtras;
19733            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19734        }
19735
19736        clearAppDataLIF(pkg, userId,
19737                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19738
19739        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19740        removeKeystoreDataIfNeeded(userId, appId);
19741
19742        UserManagerInternal umInternal = getUserManagerInternal();
19743        final int flags;
19744        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19745            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19746        } else if (umInternal.isUserRunning(userId)) {
19747            flags = StorageManager.FLAG_STORAGE_DE;
19748        } else {
19749            flags = 0;
19750        }
19751        prepareAppDataContentsLIF(pkg, userId, flags);
19752
19753        return true;
19754    }
19755
19756    /**
19757     * Reverts user permission state changes (permissions and flags) in
19758     * all packages for a given user.
19759     *
19760     * @param userId The device user for which to do a reset.
19761     */
19762    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19763        final int packageCount = mPackages.size();
19764        for (int i = 0; i < packageCount; i++) {
19765            PackageParser.Package pkg = mPackages.valueAt(i);
19766            PackageSetting ps = (PackageSetting) pkg.mExtras;
19767            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19768        }
19769    }
19770
19771    private void resetNetworkPolicies(int userId) {
19772        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19773    }
19774
19775    /**
19776     * Reverts user permission state changes (permissions and flags).
19777     *
19778     * @param ps The package for which to reset.
19779     * @param userId The device user for which to do a reset.
19780     */
19781    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19782            final PackageSetting ps, final int userId) {
19783        if (ps.pkg == null) {
19784            return;
19785        }
19786
19787        // These are flags that can change base on user actions.
19788        final int userSettableMask = FLAG_PERMISSION_USER_SET
19789                | FLAG_PERMISSION_USER_FIXED
19790                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19791                | FLAG_PERMISSION_REVIEW_REQUIRED;
19792
19793        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19794                | FLAG_PERMISSION_POLICY_FIXED;
19795
19796        boolean writeInstallPermissions = false;
19797        boolean writeRuntimePermissions = false;
19798
19799        final int permissionCount = ps.pkg.requestedPermissions.size();
19800        for (int i = 0; i < permissionCount; i++) {
19801            String permission = ps.pkg.requestedPermissions.get(i);
19802
19803            BasePermission bp = mSettings.mPermissions.get(permission);
19804            if (bp == null) {
19805                continue;
19806            }
19807
19808            // If shared user we just reset the state to which only this app contributed.
19809            if (ps.sharedUser != null) {
19810                boolean used = false;
19811                final int packageCount = ps.sharedUser.packages.size();
19812                for (int j = 0; j < packageCount; j++) {
19813                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19814                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19815                            && pkg.pkg.requestedPermissions.contains(permission)) {
19816                        used = true;
19817                        break;
19818                    }
19819                }
19820                if (used) {
19821                    continue;
19822                }
19823            }
19824
19825            PermissionsState permissionsState = ps.getPermissionsState();
19826
19827            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19828
19829            // Always clear the user settable flags.
19830            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19831                    bp.name) != null;
19832            // If permission review is enabled and this is a legacy app, mark the
19833            // permission as requiring a review as this is the initial state.
19834            int flags = 0;
19835            if (mPermissionReviewRequired
19836                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19837                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19838            }
19839            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19840                if (hasInstallState) {
19841                    writeInstallPermissions = true;
19842                } else {
19843                    writeRuntimePermissions = true;
19844                }
19845            }
19846
19847            // Below is only runtime permission handling.
19848            if (!bp.isRuntime()) {
19849                continue;
19850            }
19851
19852            // Never clobber system or policy.
19853            if ((oldFlags & policyOrSystemFlags) != 0) {
19854                continue;
19855            }
19856
19857            // If this permission was granted by default, make sure it is.
19858            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19859                if (permissionsState.grantRuntimePermission(bp, userId)
19860                        != PERMISSION_OPERATION_FAILURE) {
19861                    writeRuntimePermissions = true;
19862                }
19863            // If permission review is enabled the permissions for a legacy apps
19864            // are represented as constantly granted runtime ones, so don't revoke.
19865            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19866                // Otherwise, reset the permission.
19867                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19868                switch (revokeResult) {
19869                    case PERMISSION_OPERATION_SUCCESS:
19870                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19871                        writeRuntimePermissions = true;
19872                        final int appId = ps.appId;
19873                        mHandler.post(new Runnable() {
19874                            @Override
19875                            public void run() {
19876                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19877                            }
19878                        });
19879                    } break;
19880                }
19881            }
19882        }
19883
19884        // Synchronously write as we are taking permissions away.
19885        if (writeRuntimePermissions) {
19886            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19887        }
19888
19889        // Synchronously write as we are taking permissions away.
19890        if (writeInstallPermissions) {
19891            mSettings.writeLPr();
19892        }
19893    }
19894
19895    /**
19896     * Remove entries from the keystore daemon. Will only remove it if the
19897     * {@code appId} is valid.
19898     */
19899    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19900        if (appId < 0) {
19901            return;
19902        }
19903
19904        final KeyStore keyStore = KeyStore.getInstance();
19905        if (keyStore != null) {
19906            if (userId == UserHandle.USER_ALL) {
19907                for (final int individual : sUserManager.getUserIds()) {
19908                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19909                }
19910            } else {
19911                keyStore.clearUid(UserHandle.getUid(userId, appId));
19912            }
19913        } else {
19914            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19915        }
19916    }
19917
19918    @Override
19919    public void deleteApplicationCacheFiles(final String packageName,
19920            final IPackageDataObserver observer) {
19921        final int userId = UserHandle.getCallingUserId();
19922        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19923    }
19924
19925    @Override
19926    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19927            final IPackageDataObserver observer) {
19928        final int callingUid = Binder.getCallingUid();
19929        mContext.enforceCallingOrSelfPermission(
19930                android.Manifest.permission.DELETE_CACHE_FILES, null);
19931        enforceCrossUserPermission(callingUid, userId,
19932                /* requireFullPermission= */ true, /* checkShell= */ false,
19933                "delete application cache files");
19934        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19935                android.Manifest.permission.ACCESS_INSTANT_APPS);
19936
19937        final PackageParser.Package pkg;
19938        synchronized (mPackages) {
19939            pkg = mPackages.get(packageName);
19940        }
19941
19942        // Queue up an async operation since the package deletion may take a little while.
19943        mHandler.post(new Runnable() {
19944            public void run() {
19945                final PackageSetting ps = (PackageSetting) pkg.mExtras;
19946                boolean doClearData = true;
19947                if (ps != null) {
19948                    final boolean targetIsInstantApp =
19949                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19950                    doClearData = !targetIsInstantApp
19951                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19952                }
19953                if (doClearData) {
19954                    synchronized (mInstallLock) {
19955                        final int flags = StorageManager.FLAG_STORAGE_DE
19956                                | StorageManager.FLAG_STORAGE_CE;
19957                        // We're only clearing cache files, so we don't care if the
19958                        // app is unfrozen and still able to run
19959                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19960                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19961                    }
19962                    clearExternalStorageDataSync(packageName, userId, false);
19963                }
19964                if (observer != null) {
19965                    try {
19966                        observer.onRemoveCompleted(packageName, true);
19967                    } catch (RemoteException e) {
19968                        Log.i(TAG, "Observer no longer exists.");
19969                    }
19970                }
19971            }
19972        });
19973    }
19974
19975    @Override
19976    public void getPackageSizeInfo(final String packageName, int userHandle,
19977            final IPackageStatsObserver observer) {
19978        throw new UnsupportedOperationException(
19979                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19980    }
19981
19982    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19983        final PackageSetting ps;
19984        synchronized (mPackages) {
19985            ps = mSettings.mPackages.get(packageName);
19986            if (ps == null) {
19987                Slog.w(TAG, "Failed to find settings for " + packageName);
19988                return false;
19989            }
19990        }
19991
19992        final String[] packageNames = { packageName };
19993        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19994        final String[] codePaths = { ps.codePathString };
19995
19996        try {
19997            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19998                    ps.appId, ceDataInodes, codePaths, stats);
19999
20000            // For now, ignore code size of packages on system partition
20001            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20002                stats.codeSize = 0;
20003            }
20004
20005            // External clients expect these to be tracked separately
20006            stats.dataSize -= stats.cacheSize;
20007
20008        } catch (InstallerException e) {
20009            Slog.w(TAG, String.valueOf(e));
20010            return false;
20011        }
20012
20013        return true;
20014    }
20015
20016    private int getUidTargetSdkVersionLockedLPr(int uid) {
20017        Object obj = mSettings.getUserIdLPr(uid);
20018        if (obj instanceof SharedUserSetting) {
20019            final SharedUserSetting sus = (SharedUserSetting) obj;
20020            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20021            final Iterator<PackageSetting> it = sus.packages.iterator();
20022            while (it.hasNext()) {
20023                final PackageSetting ps = it.next();
20024                if (ps.pkg != null) {
20025                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20026                    if (v < vers) vers = v;
20027                }
20028            }
20029            return vers;
20030        } else if (obj instanceof PackageSetting) {
20031            final PackageSetting ps = (PackageSetting) obj;
20032            if (ps.pkg != null) {
20033                return ps.pkg.applicationInfo.targetSdkVersion;
20034            }
20035        }
20036        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20037    }
20038
20039    @Override
20040    public void addPreferredActivity(IntentFilter filter, int match,
20041            ComponentName[] set, ComponentName activity, int userId) {
20042        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20043                "Adding preferred");
20044    }
20045
20046    private void addPreferredActivityInternal(IntentFilter filter, int match,
20047            ComponentName[] set, ComponentName activity, boolean always, int userId,
20048            String opname) {
20049        // writer
20050        int callingUid = Binder.getCallingUid();
20051        enforceCrossUserPermission(callingUid, userId,
20052                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20053        if (filter.countActions() == 0) {
20054            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20055            return;
20056        }
20057        synchronized (mPackages) {
20058            if (mContext.checkCallingOrSelfPermission(
20059                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20060                    != PackageManager.PERMISSION_GRANTED) {
20061                if (getUidTargetSdkVersionLockedLPr(callingUid)
20062                        < Build.VERSION_CODES.FROYO) {
20063                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20064                            + callingUid);
20065                    return;
20066                }
20067                mContext.enforceCallingOrSelfPermission(
20068                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20069            }
20070
20071            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20072            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20073                    + userId + ":");
20074            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20075            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20076            scheduleWritePackageRestrictionsLocked(userId);
20077            postPreferredActivityChangedBroadcast(userId);
20078        }
20079    }
20080
20081    private void postPreferredActivityChangedBroadcast(int userId) {
20082        mHandler.post(() -> {
20083            final IActivityManager am = ActivityManager.getService();
20084            if (am == null) {
20085                return;
20086            }
20087
20088            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20089            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20090            try {
20091                am.broadcastIntent(null, intent, null, null,
20092                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20093                        null, false, false, userId);
20094            } catch (RemoteException e) {
20095            }
20096        });
20097    }
20098
20099    @Override
20100    public void replacePreferredActivity(IntentFilter filter, int match,
20101            ComponentName[] set, ComponentName activity, int userId) {
20102        if (filter.countActions() != 1) {
20103            throw new IllegalArgumentException(
20104                    "replacePreferredActivity expects filter to have only 1 action.");
20105        }
20106        if (filter.countDataAuthorities() != 0
20107                || filter.countDataPaths() != 0
20108                || filter.countDataSchemes() > 1
20109                || filter.countDataTypes() != 0) {
20110            throw new IllegalArgumentException(
20111                    "replacePreferredActivity expects filter to have no data authorities, " +
20112                    "paths, or types; and at most one scheme.");
20113        }
20114
20115        final int callingUid = Binder.getCallingUid();
20116        enforceCrossUserPermission(callingUid, userId,
20117                true /* requireFullPermission */, false /* checkShell */,
20118                "replace preferred activity");
20119        synchronized (mPackages) {
20120            if (mContext.checkCallingOrSelfPermission(
20121                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20122                    != PackageManager.PERMISSION_GRANTED) {
20123                if (getUidTargetSdkVersionLockedLPr(callingUid)
20124                        < Build.VERSION_CODES.FROYO) {
20125                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20126                            + Binder.getCallingUid());
20127                    return;
20128                }
20129                mContext.enforceCallingOrSelfPermission(
20130                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20131            }
20132
20133            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20134            if (pir != null) {
20135                // Get all of the existing entries that exactly match this filter.
20136                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20137                if (existing != null && existing.size() == 1) {
20138                    PreferredActivity cur = existing.get(0);
20139                    if (DEBUG_PREFERRED) {
20140                        Slog.i(TAG, "Checking replace of preferred:");
20141                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20142                        if (!cur.mPref.mAlways) {
20143                            Slog.i(TAG, "  -- CUR; not mAlways!");
20144                        } else {
20145                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20146                            Slog.i(TAG, "  -- CUR: mSet="
20147                                    + Arrays.toString(cur.mPref.mSetComponents));
20148                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20149                            Slog.i(TAG, "  -- NEW: mMatch="
20150                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20151                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20152                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20153                        }
20154                    }
20155                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20156                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20157                            && cur.mPref.sameSet(set)) {
20158                        // Setting the preferred activity to what it happens to be already
20159                        if (DEBUG_PREFERRED) {
20160                            Slog.i(TAG, "Replacing with same preferred activity "
20161                                    + cur.mPref.mShortComponent + " for user "
20162                                    + userId + ":");
20163                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20164                        }
20165                        return;
20166                    }
20167                }
20168
20169                if (existing != null) {
20170                    if (DEBUG_PREFERRED) {
20171                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20172                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20173                    }
20174                    for (int i = 0; i < existing.size(); i++) {
20175                        PreferredActivity pa = existing.get(i);
20176                        if (DEBUG_PREFERRED) {
20177                            Slog.i(TAG, "Removing existing preferred activity "
20178                                    + pa.mPref.mComponent + ":");
20179                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20180                        }
20181                        pir.removeFilter(pa);
20182                    }
20183                }
20184            }
20185            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20186                    "Replacing preferred");
20187        }
20188    }
20189
20190    @Override
20191    public void clearPackagePreferredActivities(String packageName) {
20192        final int callingUid = Binder.getCallingUid();
20193        if (getInstantAppPackageName(callingUid) != null) {
20194            return;
20195        }
20196        // writer
20197        synchronized (mPackages) {
20198            PackageParser.Package pkg = mPackages.get(packageName);
20199            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20200                if (mContext.checkCallingOrSelfPermission(
20201                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20202                        != PackageManager.PERMISSION_GRANTED) {
20203                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20204                            < Build.VERSION_CODES.FROYO) {
20205                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20206                                + callingUid);
20207                        return;
20208                    }
20209                    mContext.enforceCallingOrSelfPermission(
20210                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20211                }
20212            }
20213            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20214            if (ps != null
20215                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20216                return;
20217            }
20218            int user = UserHandle.getCallingUserId();
20219            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20220                scheduleWritePackageRestrictionsLocked(user);
20221            }
20222        }
20223    }
20224
20225    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20226    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20227        ArrayList<PreferredActivity> removed = null;
20228        boolean changed = false;
20229        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20230            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20231            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20232            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20233                continue;
20234            }
20235            Iterator<PreferredActivity> it = pir.filterIterator();
20236            while (it.hasNext()) {
20237                PreferredActivity pa = it.next();
20238                // Mark entry for removal only if it matches the package name
20239                // and the entry is of type "always".
20240                if (packageName == null ||
20241                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20242                                && pa.mPref.mAlways)) {
20243                    if (removed == null) {
20244                        removed = new ArrayList<PreferredActivity>();
20245                    }
20246                    removed.add(pa);
20247                }
20248            }
20249            if (removed != null) {
20250                for (int j=0; j<removed.size(); j++) {
20251                    PreferredActivity pa = removed.get(j);
20252                    pir.removeFilter(pa);
20253                }
20254                changed = true;
20255            }
20256        }
20257        if (changed) {
20258            postPreferredActivityChangedBroadcast(userId);
20259        }
20260        return changed;
20261    }
20262
20263    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20264    private void clearIntentFilterVerificationsLPw(int userId) {
20265        final int packageCount = mPackages.size();
20266        for (int i = 0; i < packageCount; i++) {
20267            PackageParser.Package pkg = mPackages.valueAt(i);
20268            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20269        }
20270    }
20271
20272    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20273    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20274        if (userId == UserHandle.USER_ALL) {
20275            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20276                    sUserManager.getUserIds())) {
20277                for (int oneUserId : sUserManager.getUserIds()) {
20278                    scheduleWritePackageRestrictionsLocked(oneUserId);
20279                }
20280            }
20281        } else {
20282            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20283                scheduleWritePackageRestrictionsLocked(userId);
20284            }
20285        }
20286    }
20287
20288    /** Clears state for all users, and touches intent filter verification policy */
20289    void clearDefaultBrowserIfNeeded(String packageName) {
20290        for (int oneUserId : sUserManager.getUserIds()) {
20291            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20292        }
20293    }
20294
20295    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20296        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20297        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20298            if (packageName.equals(defaultBrowserPackageName)) {
20299                setDefaultBrowserPackageName(null, userId);
20300            }
20301        }
20302    }
20303
20304    @Override
20305    public void resetApplicationPreferences(int userId) {
20306        mContext.enforceCallingOrSelfPermission(
20307                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20308        final long identity = Binder.clearCallingIdentity();
20309        // writer
20310        try {
20311            synchronized (mPackages) {
20312                clearPackagePreferredActivitiesLPw(null, userId);
20313                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20314                // TODO: We have to reset the default SMS and Phone. This requires
20315                // significant refactoring to keep all default apps in the package
20316                // manager (cleaner but more work) or have the services provide
20317                // callbacks to the package manager to request a default app reset.
20318                applyFactoryDefaultBrowserLPw(userId);
20319                clearIntentFilterVerificationsLPw(userId);
20320                primeDomainVerificationsLPw(userId);
20321                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20322                scheduleWritePackageRestrictionsLocked(userId);
20323            }
20324            resetNetworkPolicies(userId);
20325        } finally {
20326            Binder.restoreCallingIdentity(identity);
20327        }
20328    }
20329
20330    @Override
20331    public int getPreferredActivities(List<IntentFilter> outFilters,
20332            List<ComponentName> outActivities, String packageName) {
20333        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20334            return 0;
20335        }
20336        int num = 0;
20337        final int userId = UserHandle.getCallingUserId();
20338        // reader
20339        synchronized (mPackages) {
20340            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20341            if (pir != null) {
20342                final Iterator<PreferredActivity> it = pir.filterIterator();
20343                while (it.hasNext()) {
20344                    final PreferredActivity pa = it.next();
20345                    if (packageName == null
20346                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20347                                    && pa.mPref.mAlways)) {
20348                        if (outFilters != null) {
20349                            outFilters.add(new IntentFilter(pa));
20350                        }
20351                        if (outActivities != null) {
20352                            outActivities.add(pa.mPref.mComponent);
20353                        }
20354                    }
20355                }
20356            }
20357        }
20358
20359        return num;
20360    }
20361
20362    @Override
20363    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20364            int userId) {
20365        int callingUid = Binder.getCallingUid();
20366        if (callingUid != Process.SYSTEM_UID) {
20367            throw new SecurityException(
20368                    "addPersistentPreferredActivity can only be run by the system");
20369        }
20370        if (filter.countActions() == 0) {
20371            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20372            return;
20373        }
20374        synchronized (mPackages) {
20375            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20376                    ":");
20377            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20378            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20379                    new PersistentPreferredActivity(filter, activity));
20380            scheduleWritePackageRestrictionsLocked(userId);
20381            postPreferredActivityChangedBroadcast(userId);
20382        }
20383    }
20384
20385    @Override
20386    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20387        int callingUid = Binder.getCallingUid();
20388        if (callingUid != Process.SYSTEM_UID) {
20389            throw new SecurityException(
20390                    "clearPackagePersistentPreferredActivities can only be run by the system");
20391        }
20392        ArrayList<PersistentPreferredActivity> removed = null;
20393        boolean changed = false;
20394        synchronized (mPackages) {
20395            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20396                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20397                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20398                        .valueAt(i);
20399                if (userId != thisUserId) {
20400                    continue;
20401                }
20402                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20403                while (it.hasNext()) {
20404                    PersistentPreferredActivity ppa = it.next();
20405                    // Mark entry for removal only if it matches the package name.
20406                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20407                        if (removed == null) {
20408                            removed = new ArrayList<PersistentPreferredActivity>();
20409                        }
20410                        removed.add(ppa);
20411                    }
20412                }
20413                if (removed != null) {
20414                    for (int j=0; j<removed.size(); j++) {
20415                        PersistentPreferredActivity ppa = removed.get(j);
20416                        ppir.removeFilter(ppa);
20417                    }
20418                    changed = true;
20419                }
20420            }
20421
20422            if (changed) {
20423                scheduleWritePackageRestrictionsLocked(userId);
20424                postPreferredActivityChangedBroadcast(userId);
20425            }
20426        }
20427    }
20428
20429    /**
20430     * Common machinery for picking apart a restored XML blob and passing
20431     * it to a caller-supplied functor to be applied to the running system.
20432     */
20433    private void restoreFromXml(XmlPullParser parser, int userId,
20434            String expectedStartTag, BlobXmlRestorer functor)
20435            throws IOException, XmlPullParserException {
20436        int type;
20437        while ((type = parser.next()) != XmlPullParser.START_TAG
20438                && type != XmlPullParser.END_DOCUMENT) {
20439        }
20440        if (type != XmlPullParser.START_TAG) {
20441            // oops didn't find a start tag?!
20442            if (DEBUG_BACKUP) {
20443                Slog.e(TAG, "Didn't find start tag during restore");
20444            }
20445            return;
20446        }
20447Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20448        // this is supposed to be TAG_PREFERRED_BACKUP
20449        if (!expectedStartTag.equals(parser.getName())) {
20450            if (DEBUG_BACKUP) {
20451                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20452            }
20453            return;
20454        }
20455
20456        // skip interfering stuff, then we're aligned with the backing implementation
20457        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20458Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20459        functor.apply(parser, userId);
20460    }
20461
20462    private interface BlobXmlRestorer {
20463        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20464    }
20465
20466    /**
20467     * Non-Binder method, support for the backup/restore mechanism: write the
20468     * full set of preferred activities in its canonical XML format.  Returns the
20469     * XML output as a byte array, or null if there is none.
20470     */
20471    @Override
20472    public byte[] getPreferredActivityBackup(int userId) {
20473        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20474            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20475        }
20476
20477        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20478        try {
20479            final XmlSerializer serializer = new FastXmlSerializer();
20480            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20481            serializer.startDocument(null, true);
20482            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20483
20484            synchronized (mPackages) {
20485                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20486            }
20487
20488            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20489            serializer.endDocument();
20490            serializer.flush();
20491        } catch (Exception e) {
20492            if (DEBUG_BACKUP) {
20493                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20494            }
20495            return null;
20496        }
20497
20498        return dataStream.toByteArray();
20499    }
20500
20501    @Override
20502    public void restorePreferredActivities(byte[] backup, int userId) {
20503        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20504            throw new SecurityException("Only the system may call restorePreferredActivities()");
20505        }
20506
20507        try {
20508            final XmlPullParser parser = Xml.newPullParser();
20509            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20510            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20511                    new BlobXmlRestorer() {
20512                        @Override
20513                        public void apply(XmlPullParser parser, int userId)
20514                                throws XmlPullParserException, IOException {
20515                            synchronized (mPackages) {
20516                                mSettings.readPreferredActivitiesLPw(parser, userId);
20517                            }
20518                        }
20519                    } );
20520        } catch (Exception e) {
20521            if (DEBUG_BACKUP) {
20522                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20523            }
20524        }
20525    }
20526
20527    /**
20528     * Non-Binder method, support for the backup/restore mechanism: write the
20529     * default browser (etc) settings in its canonical XML format.  Returns the default
20530     * browser XML representation as a byte array, or null if there is none.
20531     */
20532    @Override
20533    public byte[] getDefaultAppsBackup(int userId) {
20534        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20535            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20536        }
20537
20538        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20539        try {
20540            final XmlSerializer serializer = new FastXmlSerializer();
20541            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20542            serializer.startDocument(null, true);
20543            serializer.startTag(null, TAG_DEFAULT_APPS);
20544
20545            synchronized (mPackages) {
20546                mSettings.writeDefaultAppsLPr(serializer, userId);
20547            }
20548
20549            serializer.endTag(null, TAG_DEFAULT_APPS);
20550            serializer.endDocument();
20551            serializer.flush();
20552        } catch (Exception e) {
20553            if (DEBUG_BACKUP) {
20554                Slog.e(TAG, "Unable to write default apps for backup", e);
20555            }
20556            return null;
20557        }
20558
20559        return dataStream.toByteArray();
20560    }
20561
20562    @Override
20563    public void restoreDefaultApps(byte[] backup, int userId) {
20564        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20565            throw new SecurityException("Only the system may call restoreDefaultApps()");
20566        }
20567
20568        try {
20569            final XmlPullParser parser = Xml.newPullParser();
20570            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20571            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20572                    new BlobXmlRestorer() {
20573                        @Override
20574                        public void apply(XmlPullParser parser, int userId)
20575                                throws XmlPullParserException, IOException {
20576                            synchronized (mPackages) {
20577                                mSettings.readDefaultAppsLPw(parser, userId);
20578                            }
20579                        }
20580                    } );
20581        } catch (Exception e) {
20582            if (DEBUG_BACKUP) {
20583                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20584            }
20585        }
20586    }
20587
20588    @Override
20589    public byte[] getIntentFilterVerificationBackup(int userId) {
20590        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20591            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20592        }
20593
20594        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20595        try {
20596            final XmlSerializer serializer = new FastXmlSerializer();
20597            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20598            serializer.startDocument(null, true);
20599            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20600
20601            synchronized (mPackages) {
20602                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20603            }
20604
20605            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20606            serializer.endDocument();
20607            serializer.flush();
20608        } catch (Exception e) {
20609            if (DEBUG_BACKUP) {
20610                Slog.e(TAG, "Unable to write default apps for backup", e);
20611            }
20612            return null;
20613        }
20614
20615        return dataStream.toByteArray();
20616    }
20617
20618    @Override
20619    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20620        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20621            throw new SecurityException("Only the system may call restorePreferredActivities()");
20622        }
20623
20624        try {
20625            final XmlPullParser parser = Xml.newPullParser();
20626            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20627            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20628                    new BlobXmlRestorer() {
20629                        @Override
20630                        public void apply(XmlPullParser parser, int userId)
20631                                throws XmlPullParserException, IOException {
20632                            synchronized (mPackages) {
20633                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20634                                mSettings.writeLPr();
20635                            }
20636                        }
20637                    } );
20638        } catch (Exception e) {
20639            if (DEBUG_BACKUP) {
20640                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20641            }
20642        }
20643    }
20644
20645    @Override
20646    public byte[] getPermissionGrantBackup(int userId) {
20647        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20648            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20649        }
20650
20651        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20652        try {
20653            final XmlSerializer serializer = new FastXmlSerializer();
20654            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20655            serializer.startDocument(null, true);
20656            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20657
20658            synchronized (mPackages) {
20659                serializeRuntimePermissionGrantsLPr(serializer, userId);
20660            }
20661
20662            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20663            serializer.endDocument();
20664            serializer.flush();
20665        } catch (Exception e) {
20666            if (DEBUG_BACKUP) {
20667                Slog.e(TAG, "Unable to write default apps for backup", e);
20668            }
20669            return null;
20670        }
20671
20672        return dataStream.toByteArray();
20673    }
20674
20675    @Override
20676    public void restorePermissionGrants(byte[] backup, int userId) {
20677        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20678            throw new SecurityException("Only the system may call restorePermissionGrants()");
20679        }
20680
20681        try {
20682            final XmlPullParser parser = Xml.newPullParser();
20683            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20684            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20685                    new BlobXmlRestorer() {
20686                        @Override
20687                        public void apply(XmlPullParser parser, int userId)
20688                                throws XmlPullParserException, IOException {
20689                            synchronized (mPackages) {
20690                                processRestoredPermissionGrantsLPr(parser, userId);
20691                            }
20692                        }
20693                    } );
20694        } catch (Exception e) {
20695            if (DEBUG_BACKUP) {
20696                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20697            }
20698        }
20699    }
20700
20701    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20702            throws IOException {
20703        serializer.startTag(null, TAG_ALL_GRANTS);
20704
20705        final int N = mSettings.mPackages.size();
20706        for (int i = 0; i < N; i++) {
20707            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20708            boolean pkgGrantsKnown = false;
20709
20710            PermissionsState packagePerms = ps.getPermissionsState();
20711
20712            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20713                final int grantFlags = state.getFlags();
20714                // only look at grants that are not system/policy fixed
20715                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20716                    final boolean isGranted = state.isGranted();
20717                    // And only back up the user-twiddled state bits
20718                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20719                        final String packageName = mSettings.mPackages.keyAt(i);
20720                        if (!pkgGrantsKnown) {
20721                            serializer.startTag(null, TAG_GRANT);
20722                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20723                            pkgGrantsKnown = true;
20724                        }
20725
20726                        final boolean userSet =
20727                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20728                        final boolean userFixed =
20729                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20730                        final boolean revoke =
20731                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20732
20733                        serializer.startTag(null, TAG_PERMISSION);
20734                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20735                        if (isGranted) {
20736                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20737                        }
20738                        if (userSet) {
20739                            serializer.attribute(null, ATTR_USER_SET, "true");
20740                        }
20741                        if (userFixed) {
20742                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20743                        }
20744                        if (revoke) {
20745                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20746                        }
20747                        serializer.endTag(null, TAG_PERMISSION);
20748                    }
20749                }
20750            }
20751
20752            if (pkgGrantsKnown) {
20753                serializer.endTag(null, TAG_GRANT);
20754            }
20755        }
20756
20757        serializer.endTag(null, TAG_ALL_GRANTS);
20758    }
20759
20760    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20761            throws XmlPullParserException, IOException {
20762        String pkgName = null;
20763        int outerDepth = parser.getDepth();
20764        int type;
20765        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20766                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20767            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20768                continue;
20769            }
20770
20771            final String tagName = parser.getName();
20772            if (tagName.equals(TAG_GRANT)) {
20773                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20774                if (DEBUG_BACKUP) {
20775                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20776                }
20777            } else if (tagName.equals(TAG_PERMISSION)) {
20778
20779                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20780                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20781
20782                int newFlagSet = 0;
20783                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20784                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20785                }
20786                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20787                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20788                }
20789                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20790                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20791                }
20792                if (DEBUG_BACKUP) {
20793                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20794                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20795                }
20796                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20797                if (ps != null) {
20798                    // Already installed so we apply the grant immediately
20799                    if (DEBUG_BACKUP) {
20800                        Slog.v(TAG, "        + already installed; applying");
20801                    }
20802                    PermissionsState perms = ps.getPermissionsState();
20803                    BasePermission bp = mSettings.mPermissions.get(permName);
20804                    if (bp != null) {
20805                        if (isGranted) {
20806                            perms.grantRuntimePermission(bp, userId);
20807                        }
20808                        if (newFlagSet != 0) {
20809                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20810                        }
20811                    }
20812                } else {
20813                    // Need to wait for post-restore install to apply the grant
20814                    if (DEBUG_BACKUP) {
20815                        Slog.v(TAG, "        - not yet installed; saving for later");
20816                    }
20817                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20818                            isGranted, newFlagSet, userId);
20819                }
20820            } else {
20821                PackageManagerService.reportSettingsProblem(Log.WARN,
20822                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20823                XmlUtils.skipCurrentTag(parser);
20824            }
20825        }
20826
20827        scheduleWriteSettingsLocked();
20828        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20829    }
20830
20831    @Override
20832    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20833            int sourceUserId, int targetUserId, int flags) {
20834        mContext.enforceCallingOrSelfPermission(
20835                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20836        int callingUid = Binder.getCallingUid();
20837        enforceOwnerRights(ownerPackage, callingUid);
20838        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20839        if (intentFilter.countActions() == 0) {
20840            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20841            return;
20842        }
20843        synchronized (mPackages) {
20844            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20845                    ownerPackage, targetUserId, flags);
20846            CrossProfileIntentResolver resolver =
20847                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20848            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20849            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20850            if (existing != null) {
20851                int size = existing.size();
20852                for (int i = 0; i < size; i++) {
20853                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20854                        return;
20855                    }
20856                }
20857            }
20858            resolver.addFilter(newFilter);
20859            scheduleWritePackageRestrictionsLocked(sourceUserId);
20860        }
20861    }
20862
20863    @Override
20864    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20865        mContext.enforceCallingOrSelfPermission(
20866                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20867        final int callingUid = Binder.getCallingUid();
20868        enforceOwnerRights(ownerPackage, callingUid);
20869        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20870        synchronized (mPackages) {
20871            CrossProfileIntentResolver resolver =
20872                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20873            ArraySet<CrossProfileIntentFilter> set =
20874                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20875            for (CrossProfileIntentFilter filter : set) {
20876                if (filter.getOwnerPackage().equals(ownerPackage)) {
20877                    resolver.removeFilter(filter);
20878                }
20879            }
20880            scheduleWritePackageRestrictionsLocked(sourceUserId);
20881        }
20882    }
20883
20884    // Enforcing that callingUid is owning pkg on userId
20885    private void enforceOwnerRights(String pkg, int callingUid) {
20886        // The system owns everything.
20887        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20888            return;
20889        }
20890        final int callingUserId = UserHandle.getUserId(callingUid);
20891        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20892        if (pi == null) {
20893            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20894                    + callingUserId);
20895        }
20896        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20897            throw new SecurityException("Calling uid " + callingUid
20898                    + " does not own package " + pkg);
20899        }
20900    }
20901
20902    @Override
20903    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20904        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20905            return null;
20906        }
20907        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20908    }
20909
20910    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20911        UserManagerService ums = UserManagerService.getInstance();
20912        if (ums != null) {
20913            final UserInfo parent = ums.getProfileParent(userId);
20914            final int launcherUid = (parent != null) ? parent.id : userId;
20915            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20916            if (launcherComponent != null) {
20917                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20918                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20919                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20920                        .setPackage(launcherComponent.getPackageName());
20921                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20922            }
20923        }
20924    }
20925
20926    /**
20927     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20928     * then reports the most likely home activity or null if there are more than one.
20929     */
20930    private ComponentName getDefaultHomeActivity(int userId) {
20931        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20932        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20933        if (cn != null) {
20934            return cn;
20935        }
20936
20937        // Find the launcher with the highest priority and return that component if there are no
20938        // other home activity with the same priority.
20939        int lastPriority = Integer.MIN_VALUE;
20940        ComponentName lastComponent = null;
20941        final int size = allHomeCandidates.size();
20942        for (int i = 0; i < size; i++) {
20943            final ResolveInfo ri = allHomeCandidates.get(i);
20944            if (ri.priority > lastPriority) {
20945                lastComponent = ri.activityInfo.getComponentName();
20946                lastPriority = ri.priority;
20947            } else if (ri.priority == lastPriority) {
20948                // Two components found with same priority.
20949                lastComponent = null;
20950            }
20951        }
20952        return lastComponent;
20953    }
20954
20955    private Intent getHomeIntent() {
20956        Intent intent = new Intent(Intent.ACTION_MAIN);
20957        intent.addCategory(Intent.CATEGORY_HOME);
20958        intent.addCategory(Intent.CATEGORY_DEFAULT);
20959        return intent;
20960    }
20961
20962    private IntentFilter getHomeFilter() {
20963        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20964        filter.addCategory(Intent.CATEGORY_HOME);
20965        filter.addCategory(Intent.CATEGORY_DEFAULT);
20966        return filter;
20967    }
20968
20969    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20970            int userId) {
20971        Intent intent  = getHomeIntent();
20972        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20973                PackageManager.GET_META_DATA, userId);
20974        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20975                true, false, false, userId);
20976
20977        allHomeCandidates.clear();
20978        if (list != null) {
20979            for (ResolveInfo ri : list) {
20980                allHomeCandidates.add(ri);
20981            }
20982        }
20983        return (preferred == null || preferred.activityInfo == null)
20984                ? null
20985                : new ComponentName(preferred.activityInfo.packageName,
20986                        preferred.activityInfo.name);
20987    }
20988
20989    @Override
20990    public void setHomeActivity(ComponentName comp, int userId) {
20991        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20992            return;
20993        }
20994        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20995        getHomeActivitiesAsUser(homeActivities, userId);
20996
20997        boolean found = false;
20998
20999        final int size = homeActivities.size();
21000        final ComponentName[] set = new ComponentName[size];
21001        for (int i = 0; i < size; i++) {
21002            final ResolveInfo candidate = homeActivities.get(i);
21003            final ActivityInfo info = candidate.activityInfo;
21004            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21005            set[i] = activityName;
21006            if (!found && activityName.equals(comp)) {
21007                found = true;
21008            }
21009        }
21010        if (!found) {
21011            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21012                    + userId);
21013        }
21014        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21015                set, comp, userId);
21016    }
21017
21018    private @Nullable String getSetupWizardPackageName() {
21019        final Intent intent = new Intent(Intent.ACTION_MAIN);
21020        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21021
21022        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21023                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21024                        | MATCH_DISABLED_COMPONENTS,
21025                UserHandle.myUserId());
21026        if (matches.size() == 1) {
21027            return matches.get(0).getComponentInfo().packageName;
21028        } else {
21029            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21030                    + ": matches=" + matches);
21031            return null;
21032        }
21033    }
21034
21035    private @Nullable String getStorageManagerPackageName() {
21036        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21037
21038        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21039                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21040                        | MATCH_DISABLED_COMPONENTS,
21041                UserHandle.myUserId());
21042        if (matches.size() == 1) {
21043            return matches.get(0).getComponentInfo().packageName;
21044        } else {
21045            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21046                    + matches.size() + ": matches=" + matches);
21047            return null;
21048        }
21049    }
21050
21051    @Override
21052    public void setApplicationEnabledSetting(String appPackageName,
21053            int newState, int flags, int userId, String callingPackage) {
21054        if (!sUserManager.exists(userId)) return;
21055        if (callingPackage == null) {
21056            callingPackage = Integer.toString(Binder.getCallingUid());
21057        }
21058        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21059    }
21060
21061    @Override
21062    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21063        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21064        synchronized (mPackages) {
21065            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21066            if (pkgSetting != null) {
21067                pkgSetting.setUpdateAvailable(updateAvailable);
21068            }
21069        }
21070    }
21071
21072    @Override
21073    public void setComponentEnabledSetting(ComponentName componentName,
21074            int newState, int flags, int userId) {
21075        if (!sUserManager.exists(userId)) return;
21076        setEnabledSetting(componentName.getPackageName(),
21077                componentName.getClassName(), newState, flags, userId, null);
21078    }
21079
21080    private void setEnabledSetting(final String packageName, String className, int newState,
21081            final int flags, int userId, String callingPackage) {
21082        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21083              || newState == COMPONENT_ENABLED_STATE_ENABLED
21084              || newState == COMPONENT_ENABLED_STATE_DISABLED
21085              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21086              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21087            throw new IllegalArgumentException("Invalid new component state: "
21088                    + newState);
21089        }
21090        PackageSetting pkgSetting;
21091        final int callingUid = Binder.getCallingUid();
21092        final int permission;
21093        if (callingUid == Process.SYSTEM_UID) {
21094            permission = PackageManager.PERMISSION_GRANTED;
21095        } else {
21096            permission = mContext.checkCallingOrSelfPermission(
21097                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21098        }
21099        enforceCrossUserPermission(callingUid, userId,
21100                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21101        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21102        boolean sendNow = false;
21103        boolean isApp = (className == null);
21104        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21105        String componentName = isApp ? packageName : className;
21106        int packageUid = -1;
21107        ArrayList<String> components;
21108
21109        // reader
21110        synchronized (mPackages) {
21111            pkgSetting = mSettings.mPackages.get(packageName);
21112            if (pkgSetting == null) {
21113                if (!isCallerInstantApp) {
21114                    if (className == null) {
21115                        throw new IllegalArgumentException("Unknown package: " + packageName);
21116                    }
21117                    throw new IllegalArgumentException(
21118                            "Unknown component: " + packageName + "/" + className);
21119                } else {
21120                    // throw SecurityException to prevent leaking package information
21121                    throw new SecurityException(
21122                            "Attempt to change component state; "
21123                            + "pid=" + Binder.getCallingPid()
21124                            + ", uid=" + callingUid
21125                            + (className == null
21126                                    ? ", package=" + packageName
21127                                    : ", component=" + packageName + "/" + className));
21128                }
21129            }
21130        }
21131
21132        // Limit who can change which apps
21133        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21134            // Don't allow apps that don't have permission to modify other apps
21135            if (!allowedByPermission) {
21136                throw new SecurityException(
21137                        "Attempt to change component state; "
21138                        + "pid=" + Binder.getCallingPid()
21139                        + ", uid=" + callingUid
21140                        + (className == null
21141                                ? ", package=" + packageName
21142                                : ", component=" + packageName + "/" + className));
21143            }
21144            // Don't allow changing protected packages.
21145            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21146                throw new SecurityException("Cannot disable a protected package: " + packageName);
21147            }
21148        }
21149
21150        synchronized (mPackages) {
21151            if (callingUid == Process.SHELL_UID
21152                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21153                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21154                // unless it is a test package.
21155                int oldState = pkgSetting.getEnabled(userId);
21156                if (className == null
21157                    &&
21158                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21159                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21160                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21161                    &&
21162                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21163                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21164                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21165                    // ok
21166                } else {
21167                    throw new SecurityException(
21168                            "Shell cannot change component state for " + packageName + "/"
21169                            + className + " to " + newState);
21170                }
21171            }
21172            if (className == null) {
21173                // We're dealing with an application/package level state change
21174                if (pkgSetting.getEnabled(userId) == newState) {
21175                    // Nothing to do
21176                    return;
21177                }
21178                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21179                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21180                    // Don't care about who enables an app.
21181                    callingPackage = null;
21182                }
21183                pkgSetting.setEnabled(newState, userId, callingPackage);
21184                // pkgSetting.pkg.mSetEnabled = newState;
21185            } else {
21186                // We're dealing with a component level state change
21187                // First, verify that this is a valid class name.
21188                PackageParser.Package pkg = pkgSetting.pkg;
21189                if (pkg == null || !pkg.hasComponentClassName(className)) {
21190                    if (pkg != null &&
21191                            pkg.applicationInfo.targetSdkVersion >=
21192                                    Build.VERSION_CODES.JELLY_BEAN) {
21193                        throw new IllegalArgumentException("Component class " + className
21194                                + " does not exist in " + packageName);
21195                    } else {
21196                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21197                                + className + " does not exist in " + packageName);
21198                    }
21199                }
21200                switch (newState) {
21201                case COMPONENT_ENABLED_STATE_ENABLED:
21202                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21203                        return;
21204                    }
21205                    break;
21206                case COMPONENT_ENABLED_STATE_DISABLED:
21207                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21208                        return;
21209                    }
21210                    break;
21211                case COMPONENT_ENABLED_STATE_DEFAULT:
21212                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21213                        return;
21214                    }
21215                    break;
21216                default:
21217                    Slog.e(TAG, "Invalid new component state: " + newState);
21218                    return;
21219                }
21220            }
21221            scheduleWritePackageRestrictionsLocked(userId);
21222            updateSequenceNumberLP(packageName, new int[] { userId });
21223            final long callingId = Binder.clearCallingIdentity();
21224            try {
21225                updateInstantAppInstallerLocked(packageName);
21226            } finally {
21227                Binder.restoreCallingIdentity(callingId);
21228            }
21229            components = mPendingBroadcasts.get(userId, packageName);
21230            final boolean newPackage = components == null;
21231            if (newPackage) {
21232                components = new ArrayList<String>();
21233            }
21234            if (!components.contains(componentName)) {
21235                components.add(componentName);
21236            }
21237            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21238                sendNow = true;
21239                // Purge entry from pending broadcast list if another one exists already
21240                // since we are sending one right away.
21241                mPendingBroadcasts.remove(userId, packageName);
21242            } else {
21243                if (newPackage) {
21244                    mPendingBroadcasts.put(userId, packageName, components);
21245                }
21246                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21247                    // Schedule a message
21248                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21249                }
21250            }
21251        }
21252
21253        long callingId = Binder.clearCallingIdentity();
21254        try {
21255            if (sendNow) {
21256                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21257                sendPackageChangedBroadcast(packageName,
21258                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21259            }
21260        } finally {
21261            Binder.restoreCallingIdentity(callingId);
21262        }
21263    }
21264
21265    @Override
21266    public void flushPackageRestrictionsAsUser(int userId) {
21267        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21268            return;
21269        }
21270        if (!sUserManager.exists(userId)) {
21271            return;
21272        }
21273        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21274                false /* checkShell */, "flushPackageRestrictions");
21275        synchronized (mPackages) {
21276            mSettings.writePackageRestrictionsLPr(userId);
21277            mDirtyUsers.remove(userId);
21278            if (mDirtyUsers.isEmpty()) {
21279                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21280            }
21281        }
21282    }
21283
21284    private void sendPackageChangedBroadcast(String packageName,
21285            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21286        if (DEBUG_INSTALL)
21287            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21288                    + componentNames);
21289        Bundle extras = new Bundle(4);
21290        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21291        String nameList[] = new String[componentNames.size()];
21292        componentNames.toArray(nameList);
21293        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21294        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21295        extras.putInt(Intent.EXTRA_UID, packageUid);
21296        // If this is not reporting a change of the overall package, then only send it
21297        // to registered receivers.  We don't want to launch a swath of apps for every
21298        // little component state change.
21299        final int flags = !componentNames.contains(packageName)
21300                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21301        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21302                new int[] {UserHandle.getUserId(packageUid)});
21303    }
21304
21305    @Override
21306    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21307        if (!sUserManager.exists(userId)) return;
21308        final int callingUid = Binder.getCallingUid();
21309        if (getInstantAppPackageName(callingUid) != null) {
21310            return;
21311        }
21312        final int permission = mContext.checkCallingOrSelfPermission(
21313                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21314        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21315        enforceCrossUserPermission(callingUid, userId,
21316                true /* requireFullPermission */, true /* checkShell */, "stop package");
21317        // writer
21318        synchronized (mPackages) {
21319            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21320                    allowedByPermission, callingUid, userId)) {
21321                scheduleWritePackageRestrictionsLocked(userId);
21322            }
21323        }
21324    }
21325
21326    @Override
21327    public String getInstallerPackageName(String packageName) {
21328        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21329            return null;
21330        }
21331        // reader
21332        synchronized (mPackages) {
21333            return mSettings.getInstallerPackageNameLPr(packageName);
21334        }
21335    }
21336
21337    public boolean isOrphaned(String packageName) {
21338        // reader
21339        synchronized (mPackages) {
21340            return mSettings.isOrphaned(packageName);
21341        }
21342    }
21343
21344    @Override
21345    public int getApplicationEnabledSetting(String packageName, int userId) {
21346        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21347        int callingUid = Binder.getCallingUid();
21348        enforceCrossUserPermission(callingUid, userId,
21349                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21350        // reader
21351        synchronized (mPackages) {
21352            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21353                return COMPONENT_ENABLED_STATE_DISABLED;
21354            }
21355            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21356        }
21357    }
21358
21359    @Override
21360    public int getComponentEnabledSetting(ComponentName component, int userId) {
21361        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21362        int callingUid = Binder.getCallingUid();
21363        enforceCrossUserPermission(callingUid, userId,
21364                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21365        synchronized (mPackages) {
21366            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21367                    component, TYPE_UNKNOWN, userId)) {
21368                return COMPONENT_ENABLED_STATE_DISABLED;
21369            }
21370            return mSettings.getComponentEnabledSettingLPr(component, userId);
21371        }
21372    }
21373
21374    @Override
21375    public void enterSafeMode() {
21376        enforceSystemOrRoot("Only the system can request entering safe mode");
21377
21378        if (!mSystemReady) {
21379            mSafeMode = true;
21380        }
21381    }
21382
21383    @Override
21384    public void systemReady() {
21385        enforceSystemOrRoot("Only the system can claim the system is ready");
21386
21387        mSystemReady = true;
21388        final ContentResolver resolver = mContext.getContentResolver();
21389        ContentObserver co = new ContentObserver(mHandler) {
21390            @Override
21391            public void onChange(boolean selfChange) {
21392                mEphemeralAppsDisabled =
21393                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21394                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21395            }
21396        };
21397        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21398                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21399                false, co, UserHandle.USER_SYSTEM);
21400        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21401                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21402        co.onChange(true);
21403
21404        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21405        // disabled after already being started.
21406        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21407                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21408
21409        // Read the compatibilty setting when the system is ready.
21410        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21411                mContext.getContentResolver(),
21412                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21413        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21414        if (DEBUG_SETTINGS) {
21415            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21416        }
21417
21418        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21419
21420        synchronized (mPackages) {
21421            // Verify that all of the preferred activity components actually
21422            // exist.  It is possible for applications to be updated and at
21423            // that point remove a previously declared activity component that
21424            // had been set as a preferred activity.  We try to clean this up
21425            // the next time we encounter that preferred activity, but it is
21426            // possible for the user flow to never be able to return to that
21427            // situation so here we do a sanity check to make sure we haven't
21428            // left any junk around.
21429            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21430            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21431                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21432                removed.clear();
21433                for (PreferredActivity pa : pir.filterSet()) {
21434                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21435                        removed.add(pa);
21436                    }
21437                }
21438                if (removed.size() > 0) {
21439                    for (int r=0; r<removed.size(); r++) {
21440                        PreferredActivity pa = removed.get(r);
21441                        Slog.w(TAG, "Removing dangling preferred activity: "
21442                                + pa.mPref.mComponent);
21443                        pir.removeFilter(pa);
21444                    }
21445                    mSettings.writePackageRestrictionsLPr(
21446                            mSettings.mPreferredActivities.keyAt(i));
21447                }
21448            }
21449
21450            for (int userId : UserManagerService.getInstance().getUserIds()) {
21451                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21452                    grantPermissionsUserIds = ArrayUtils.appendInt(
21453                            grantPermissionsUserIds, userId);
21454                }
21455            }
21456        }
21457        sUserManager.systemReady();
21458
21459        // If we upgraded grant all default permissions before kicking off.
21460        for (int userId : grantPermissionsUserIds) {
21461            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21462        }
21463
21464        // If we did not grant default permissions, we preload from this the
21465        // default permission exceptions lazily to ensure we don't hit the
21466        // disk on a new user creation.
21467        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21468            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21469        }
21470
21471        // Kick off any messages waiting for system ready
21472        if (mPostSystemReadyMessages != null) {
21473            for (Message msg : mPostSystemReadyMessages) {
21474                msg.sendToTarget();
21475            }
21476            mPostSystemReadyMessages = null;
21477        }
21478
21479        // Watch for external volumes that come and go over time
21480        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21481        storage.registerListener(mStorageListener);
21482
21483        mInstallerService.systemReady();
21484        mPackageDexOptimizer.systemReady();
21485
21486        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21487                StorageManagerInternal.class);
21488        StorageManagerInternal.addExternalStoragePolicy(
21489                new StorageManagerInternal.ExternalStorageMountPolicy() {
21490            @Override
21491            public int getMountMode(int uid, String packageName) {
21492                if (Process.isIsolated(uid)) {
21493                    return Zygote.MOUNT_EXTERNAL_NONE;
21494                }
21495                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21496                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21497                }
21498                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21499                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21500                }
21501                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21502                    return Zygote.MOUNT_EXTERNAL_READ;
21503                }
21504                return Zygote.MOUNT_EXTERNAL_WRITE;
21505            }
21506
21507            @Override
21508            public boolean hasExternalStorage(int uid, String packageName) {
21509                return true;
21510            }
21511        });
21512
21513        // Now that we're mostly running, clean up stale users and apps
21514        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21515        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21516
21517        if (mPrivappPermissionsViolations != null) {
21518            Slog.wtf(TAG,"Signature|privileged permissions not in "
21519                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21520            mPrivappPermissionsViolations = null;
21521        }
21522    }
21523
21524    public void waitForAppDataPrepared() {
21525        if (mPrepareAppDataFuture == null) {
21526            return;
21527        }
21528        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21529        mPrepareAppDataFuture = null;
21530    }
21531
21532    @Override
21533    public boolean isSafeMode() {
21534        // allow instant applications
21535        return mSafeMode;
21536    }
21537
21538    @Override
21539    public boolean hasSystemUidErrors() {
21540        // allow instant applications
21541        return mHasSystemUidErrors;
21542    }
21543
21544    static String arrayToString(int[] array) {
21545        StringBuffer buf = new StringBuffer(128);
21546        buf.append('[');
21547        if (array != null) {
21548            for (int i=0; i<array.length; i++) {
21549                if (i > 0) buf.append(", ");
21550                buf.append(array[i]);
21551            }
21552        }
21553        buf.append(']');
21554        return buf.toString();
21555    }
21556
21557    static class DumpState {
21558        public static final int DUMP_LIBS = 1 << 0;
21559        public static final int DUMP_FEATURES = 1 << 1;
21560        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21561        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21562        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21563        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21564        public static final int DUMP_PERMISSIONS = 1 << 6;
21565        public static final int DUMP_PACKAGES = 1 << 7;
21566        public static final int DUMP_SHARED_USERS = 1 << 8;
21567        public static final int DUMP_MESSAGES = 1 << 9;
21568        public static final int DUMP_PROVIDERS = 1 << 10;
21569        public static final int DUMP_VERIFIERS = 1 << 11;
21570        public static final int DUMP_PREFERRED = 1 << 12;
21571        public static final int DUMP_PREFERRED_XML = 1 << 13;
21572        public static final int DUMP_KEYSETS = 1 << 14;
21573        public static final int DUMP_VERSION = 1 << 15;
21574        public static final int DUMP_INSTALLS = 1 << 16;
21575        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21576        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21577        public static final int DUMP_FROZEN = 1 << 19;
21578        public static final int DUMP_DEXOPT = 1 << 20;
21579        public static final int DUMP_COMPILER_STATS = 1 << 21;
21580        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
21581        public static final int DUMP_CHANGES = 1 << 23;
21582
21583        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21584
21585        private int mTypes;
21586
21587        private int mOptions;
21588
21589        private boolean mTitlePrinted;
21590
21591        private SharedUserSetting mSharedUser;
21592
21593        public boolean isDumping(int type) {
21594            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21595                return true;
21596            }
21597
21598            return (mTypes & type) != 0;
21599        }
21600
21601        public void setDump(int type) {
21602            mTypes |= type;
21603        }
21604
21605        public boolean isOptionEnabled(int option) {
21606            return (mOptions & option) != 0;
21607        }
21608
21609        public void setOptionEnabled(int option) {
21610            mOptions |= option;
21611        }
21612
21613        public boolean onTitlePrinted() {
21614            final boolean printed = mTitlePrinted;
21615            mTitlePrinted = true;
21616            return printed;
21617        }
21618
21619        public boolean getTitlePrinted() {
21620            return mTitlePrinted;
21621        }
21622
21623        public void setTitlePrinted(boolean enabled) {
21624            mTitlePrinted = enabled;
21625        }
21626
21627        public SharedUserSetting getSharedUser() {
21628            return mSharedUser;
21629        }
21630
21631        public void setSharedUser(SharedUserSetting user) {
21632            mSharedUser = user;
21633        }
21634    }
21635
21636    @Override
21637    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21638            FileDescriptor err, String[] args, ShellCallback callback,
21639            ResultReceiver resultReceiver) {
21640        (new PackageManagerShellCommand(this)).exec(
21641                this, in, out, err, args, callback, resultReceiver);
21642    }
21643
21644    @Override
21645    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21646        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21647
21648        DumpState dumpState = new DumpState();
21649        boolean fullPreferred = false;
21650        boolean checkin = false;
21651
21652        String packageName = null;
21653        ArraySet<String> permissionNames = null;
21654
21655        int opti = 0;
21656        while (opti < args.length) {
21657            String opt = args[opti];
21658            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21659                break;
21660            }
21661            opti++;
21662
21663            if ("-a".equals(opt)) {
21664                // Right now we only know how to print all.
21665            } else if ("-h".equals(opt)) {
21666                pw.println("Package manager dump options:");
21667                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21668                pw.println("    --checkin: dump for a checkin");
21669                pw.println("    -f: print details of intent filters");
21670                pw.println("    -h: print this help");
21671                pw.println("  cmd may be one of:");
21672                pw.println("    l[ibraries]: list known shared libraries");
21673                pw.println("    f[eatures]: list device features");
21674                pw.println("    k[eysets]: print known keysets");
21675                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21676                pw.println("    perm[issions]: dump permissions");
21677                pw.println("    permission [name ...]: dump declaration and use of given permission");
21678                pw.println("    pref[erred]: print preferred package settings");
21679                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21680                pw.println("    prov[iders]: dump content providers");
21681                pw.println("    p[ackages]: dump installed packages");
21682                pw.println("    s[hared-users]: dump shared user IDs");
21683                pw.println("    m[essages]: print collected runtime messages");
21684                pw.println("    v[erifiers]: print package verifier info");
21685                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21686                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21687                pw.println("    version: print database version info");
21688                pw.println("    write: write current settings now");
21689                pw.println("    installs: details about install sessions");
21690                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21691                pw.println("    dexopt: dump dexopt state");
21692                pw.println("    compiler-stats: dump compiler statistics");
21693                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21694                pw.println("    <package.name>: info about given package");
21695                return;
21696            } else if ("--checkin".equals(opt)) {
21697                checkin = true;
21698            } else if ("-f".equals(opt)) {
21699                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21700            } else if ("--proto".equals(opt)) {
21701                dumpProto(fd);
21702                return;
21703            } else {
21704                pw.println("Unknown argument: " + opt + "; use -h for help");
21705            }
21706        }
21707
21708        // Is the caller requesting to dump a particular piece of data?
21709        if (opti < args.length) {
21710            String cmd = args[opti];
21711            opti++;
21712            // Is this a package name?
21713            if ("android".equals(cmd) || cmd.contains(".")) {
21714                packageName = cmd;
21715                // When dumping a single package, we always dump all of its
21716                // filter information since the amount of data will be reasonable.
21717                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21718            } else if ("check-permission".equals(cmd)) {
21719                if (opti >= args.length) {
21720                    pw.println("Error: check-permission missing permission argument");
21721                    return;
21722                }
21723                String perm = args[opti];
21724                opti++;
21725                if (opti >= args.length) {
21726                    pw.println("Error: check-permission missing package argument");
21727                    return;
21728                }
21729
21730                String pkg = args[opti];
21731                opti++;
21732                int user = UserHandle.getUserId(Binder.getCallingUid());
21733                if (opti < args.length) {
21734                    try {
21735                        user = Integer.parseInt(args[opti]);
21736                    } catch (NumberFormatException e) {
21737                        pw.println("Error: check-permission user argument is not a number: "
21738                                + args[opti]);
21739                        return;
21740                    }
21741                }
21742
21743                // Normalize package name to handle renamed packages and static libs
21744                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21745
21746                pw.println(checkPermission(perm, pkg, user));
21747                return;
21748            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21749                dumpState.setDump(DumpState.DUMP_LIBS);
21750            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21751                dumpState.setDump(DumpState.DUMP_FEATURES);
21752            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21753                if (opti >= args.length) {
21754                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21755                            | DumpState.DUMP_SERVICE_RESOLVERS
21756                            | DumpState.DUMP_RECEIVER_RESOLVERS
21757                            | DumpState.DUMP_CONTENT_RESOLVERS);
21758                } else {
21759                    while (opti < args.length) {
21760                        String name = args[opti];
21761                        if ("a".equals(name) || "activity".equals(name)) {
21762                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21763                        } else if ("s".equals(name) || "service".equals(name)) {
21764                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21765                        } else if ("r".equals(name) || "receiver".equals(name)) {
21766                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21767                        } else if ("c".equals(name) || "content".equals(name)) {
21768                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21769                        } else {
21770                            pw.println("Error: unknown resolver table type: " + name);
21771                            return;
21772                        }
21773                        opti++;
21774                    }
21775                }
21776            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21777                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21778            } else if ("permission".equals(cmd)) {
21779                if (opti >= args.length) {
21780                    pw.println("Error: permission requires permission name");
21781                    return;
21782                }
21783                permissionNames = new ArraySet<>();
21784                while (opti < args.length) {
21785                    permissionNames.add(args[opti]);
21786                    opti++;
21787                }
21788                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21789                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21790            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21791                dumpState.setDump(DumpState.DUMP_PREFERRED);
21792            } else if ("preferred-xml".equals(cmd)) {
21793                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21794                if (opti < args.length && "--full".equals(args[opti])) {
21795                    fullPreferred = true;
21796                    opti++;
21797                }
21798            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21799                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21800            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21801                dumpState.setDump(DumpState.DUMP_PACKAGES);
21802            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21803                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21804            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21805                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21806            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21807                dumpState.setDump(DumpState.DUMP_MESSAGES);
21808            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21809                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21810            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21811                    || "intent-filter-verifiers".equals(cmd)) {
21812                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21813            } else if ("version".equals(cmd)) {
21814                dumpState.setDump(DumpState.DUMP_VERSION);
21815            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21816                dumpState.setDump(DumpState.DUMP_KEYSETS);
21817            } else if ("installs".equals(cmd)) {
21818                dumpState.setDump(DumpState.DUMP_INSTALLS);
21819            } else if ("frozen".equals(cmd)) {
21820                dumpState.setDump(DumpState.DUMP_FROZEN);
21821            } else if ("dexopt".equals(cmd)) {
21822                dumpState.setDump(DumpState.DUMP_DEXOPT);
21823            } else if ("compiler-stats".equals(cmd)) {
21824                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21825            } else if ("enabled-overlays".equals(cmd)) {
21826                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21827            } else if ("changes".equals(cmd)) {
21828                dumpState.setDump(DumpState.DUMP_CHANGES);
21829            } else if ("write".equals(cmd)) {
21830                synchronized (mPackages) {
21831                    mSettings.writeLPr();
21832                    pw.println("Settings written.");
21833                    return;
21834                }
21835            }
21836        }
21837
21838        if (checkin) {
21839            pw.println("vers,1");
21840        }
21841
21842        // reader
21843        synchronized (mPackages) {
21844            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21845                if (!checkin) {
21846                    if (dumpState.onTitlePrinted())
21847                        pw.println();
21848                    pw.println("Database versions:");
21849                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21850                }
21851            }
21852
21853            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21854                if (!checkin) {
21855                    if (dumpState.onTitlePrinted())
21856                        pw.println();
21857                    pw.println("Verifiers:");
21858                    pw.print("  Required: ");
21859                    pw.print(mRequiredVerifierPackage);
21860                    pw.print(" (uid=");
21861                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21862                            UserHandle.USER_SYSTEM));
21863                    pw.println(")");
21864                } else if (mRequiredVerifierPackage != null) {
21865                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21866                    pw.print(",");
21867                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21868                            UserHandle.USER_SYSTEM));
21869                }
21870            }
21871
21872            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21873                    packageName == null) {
21874                if (mIntentFilterVerifierComponent != null) {
21875                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21876                    if (!checkin) {
21877                        if (dumpState.onTitlePrinted())
21878                            pw.println();
21879                        pw.println("Intent Filter Verifier:");
21880                        pw.print("  Using: ");
21881                        pw.print(verifierPackageName);
21882                        pw.print(" (uid=");
21883                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21884                                UserHandle.USER_SYSTEM));
21885                        pw.println(")");
21886                    } else if (verifierPackageName != null) {
21887                        pw.print("ifv,"); pw.print(verifierPackageName);
21888                        pw.print(",");
21889                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21890                                UserHandle.USER_SYSTEM));
21891                    }
21892                } else {
21893                    pw.println();
21894                    pw.println("No Intent Filter Verifier available!");
21895                }
21896            }
21897
21898            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21899                boolean printedHeader = false;
21900                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21901                while (it.hasNext()) {
21902                    String libName = it.next();
21903                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21904                    if (versionedLib == null) {
21905                        continue;
21906                    }
21907                    final int versionCount = versionedLib.size();
21908                    for (int i = 0; i < versionCount; i++) {
21909                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21910                        if (!checkin) {
21911                            if (!printedHeader) {
21912                                if (dumpState.onTitlePrinted())
21913                                    pw.println();
21914                                pw.println("Libraries:");
21915                                printedHeader = true;
21916                            }
21917                            pw.print("  ");
21918                        } else {
21919                            pw.print("lib,");
21920                        }
21921                        pw.print(libEntry.info.getName());
21922                        if (libEntry.info.isStatic()) {
21923                            pw.print(" version=" + libEntry.info.getVersion());
21924                        }
21925                        if (!checkin) {
21926                            pw.print(" -> ");
21927                        }
21928                        if (libEntry.path != null) {
21929                            pw.print(" (jar) ");
21930                            pw.print(libEntry.path);
21931                        } else {
21932                            pw.print(" (apk) ");
21933                            pw.print(libEntry.apk);
21934                        }
21935                        pw.println();
21936                    }
21937                }
21938            }
21939
21940            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21941                if (dumpState.onTitlePrinted())
21942                    pw.println();
21943                if (!checkin) {
21944                    pw.println("Features:");
21945                }
21946
21947                synchronized (mAvailableFeatures) {
21948                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21949                        if (checkin) {
21950                            pw.print("feat,");
21951                            pw.print(feat.name);
21952                            pw.print(",");
21953                            pw.println(feat.version);
21954                        } else {
21955                            pw.print("  ");
21956                            pw.print(feat.name);
21957                            if (feat.version > 0) {
21958                                pw.print(" version=");
21959                                pw.print(feat.version);
21960                            }
21961                            pw.println();
21962                        }
21963                    }
21964                }
21965            }
21966
21967            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21968                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21969                        : "Activity Resolver Table:", "  ", packageName,
21970                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21971                    dumpState.setTitlePrinted(true);
21972                }
21973            }
21974            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21975                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21976                        : "Receiver Resolver Table:", "  ", packageName,
21977                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21978                    dumpState.setTitlePrinted(true);
21979                }
21980            }
21981            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21982                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21983                        : "Service Resolver Table:", "  ", packageName,
21984                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21985                    dumpState.setTitlePrinted(true);
21986                }
21987            }
21988            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21989                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21990                        : "Provider Resolver Table:", "  ", packageName,
21991                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21992                    dumpState.setTitlePrinted(true);
21993                }
21994            }
21995
21996            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21997                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21998                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21999                    int user = mSettings.mPreferredActivities.keyAt(i);
22000                    if (pir.dump(pw,
22001                            dumpState.getTitlePrinted()
22002                                ? "\nPreferred Activities User " + user + ":"
22003                                : "Preferred Activities User " + user + ":", "  ",
22004                            packageName, true, false)) {
22005                        dumpState.setTitlePrinted(true);
22006                    }
22007                }
22008            }
22009
22010            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22011                pw.flush();
22012                FileOutputStream fout = new FileOutputStream(fd);
22013                BufferedOutputStream str = new BufferedOutputStream(fout);
22014                XmlSerializer serializer = new FastXmlSerializer();
22015                try {
22016                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22017                    serializer.startDocument(null, true);
22018                    serializer.setFeature(
22019                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22020                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22021                    serializer.endDocument();
22022                    serializer.flush();
22023                } catch (IllegalArgumentException e) {
22024                    pw.println("Failed writing: " + e);
22025                } catch (IllegalStateException e) {
22026                    pw.println("Failed writing: " + e);
22027                } catch (IOException e) {
22028                    pw.println("Failed writing: " + e);
22029                }
22030            }
22031
22032            if (!checkin
22033                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22034                    && packageName == null) {
22035                pw.println();
22036                int count = mSettings.mPackages.size();
22037                if (count == 0) {
22038                    pw.println("No applications!");
22039                    pw.println();
22040                } else {
22041                    final String prefix = "  ";
22042                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22043                    if (allPackageSettings.size() == 0) {
22044                        pw.println("No domain preferred apps!");
22045                        pw.println();
22046                    } else {
22047                        pw.println("App verification status:");
22048                        pw.println();
22049                        count = 0;
22050                        for (PackageSetting ps : allPackageSettings) {
22051                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22052                            if (ivi == null || ivi.getPackageName() == null) continue;
22053                            pw.println(prefix + "Package: " + ivi.getPackageName());
22054                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22055                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22056                            pw.println();
22057                            count++;
22058                        }
22059                        if (count == 0) {
22060                            pw.println(prefix + "No app verification established.");
22061                            pw.println();
22062                        }
22063                        for (int userId : sUserManager.getUserIds()) {
22064                            pw.println("App linkages for user " + userId + ":");
22065                            pw.println();
22066                            count = 0;
22067                            for (PackageSetting ps : allPackageSettings) {
22068                                final long status = ps.getDomainVerificationStatusForUser(userId);
22069                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22070                                        && !DEBUG_DOMAIN_VERIFICATION) {
22071                                    continue;
22072                                }
22073                                pw.println(prefix + "Package: " + ps.name);
22074                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22075                                String statusStr = IntentFilterVerificationInfo.
22076                                        getStatusStringFromValue(status);
22077                                pw.println(prefix + "Status:  " + statusStr);
22078                                pw.println();
22079                                count++;
22080                            }
22081                            if (count == 0) {
22082                                pw.println(prefix + "No configured app linkages.");
22083                                pw.println();
22084                            }
22085                        }
22086                    }
22087                }
22088            }
22089
22090            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22091                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22092                if (packageName == null && permissionNames == null) {
22093                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22094                        if (iperm == 0) {
22095                            if (dumpState.onTitlePrinted())
22096                                pw.println();
22097                            pw.println("AppOp Permissions:");
22098                        }
22099                        pw.print("  AppOp Permission ");
22100                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22101                        pw.println(":");
22102                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22103                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22104                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22105                        }
22106                    }
22107                }
22108            }
22109
22110            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22111                boolean printedSomething = false;
22112                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22113                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22114                        continue;
22115                    }
22116                    if (!printedSomething) {
22117                        if (dumpState.onTitlePrinted())
22118                            pw.println();
22119                        pw.println("Registered ContentProviders:");
22120                        printedSomething = true;
22121                    }
22122                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22123                    pw.print("    "); pw.println(p.toString());
22124                }
22125                printedSomething = false;
22126                for (Map.Entry<String, PackageParser.Provider> entry :
22127                        mProvidersByAuthority.entrySet()) {
22128                    PackageParser.Provider p = entry.getValue();
22129                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22130                        continue;
22131                    }
22132                    if (!printedSomething) {
22133                        if (dumpState.onTitlePrinted())
22134                            pw.println();
22135                        pw.println("ContentProvider Authorities:");
22136                        printedSomething = true;
22137                    }
22138                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22139                    pw.print("    "); pw.println(p.toString());
22140                    if (p.info != null && p.info.applicationInfo != null) {
22141                        final String appInfo = p.info.applicationInfo.toString();
22142                        pw.print("      applicationInfo="); pw.println(appInfo);
22143                    }
22144                }
22145            }
22146
22147            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22148                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22149            }
22150
22151            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22152                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22153            }
22154
22155            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22156                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22157            }
22158
22159            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22160                if (dumpState.onTitlePrinted()) pw.println();
22161                pw.println("Package Changes:");
22162                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22163                final int K = mChangedPackages.size();
22164                for (int i = 0; i < K; i++) {
22165                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22166                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22167                    final int N = changes.size();
22168                    if (N == 0) {
22169                        pw.print("    "); pw.println("No packages changed");
22170                    } else {
22171                        for (int j = 0; j < N; j++) {
22172                            final String pkgName = changes.valueAt(j);
22173                            final int sequenceNumber = changes.keyAt(j);
22174                            pw.print("    ");
22175                            pw.print("seq=");
22176                            pw.print(sequenceNumber);
22177                            pw.print(", package=");
22178                            pw.println(pkgName);
22179                        }
22180                    }
22181                }
22182            }
22183
22184            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22185                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22186            }
22187
22188            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22189                // XXX should handle packageName != null by dumping only install data that
22190                // the given package is involved with.
22191                if (dumpState.onTitlePrinted()) pw.println();
22192
22193                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22194                ipw.println();
22195                ipw.println("Frozen packages:");
22196                ipw.increaseIndent();
22197                if (mFrozenPackages.size() == 0) {
22198                    ipw.println("(none)");
22199                } else {
22200                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22201                        ipw.println(mFrozenPackages.valueAt(i));
22202                    }
22203                }
22204                ipw.decreaseIndent();
22205            }
22206
22207            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22208                if (dumpState.onTitlePrinted()) pw.println();
22209                dumpDexoptStateLPr(pw, packageName);
22210            }
22211
22212            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22213                if (dumpState.onTitlePrinted()) pw.println();
22214                dumpCompilerStatsLPr(pw, packageName);
22215            }
22216
22217            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
22218                if (dumpState.onTitlePrinted()) pw.println();
22219                dumpEnabledOverlaysLPr(pw);
22220            }
22221
22222            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22223                if (dumpState.onTitlePrinted()) pw.println();
22224                mSettings.dumpReadMessagesLPr(pw, dumpState);
22225
22226                pw.println();
22227                pw.println("Package warning messages:");
22228                BufferedReader in = null;
22229                String line = null;
22230                try {
22231                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22232                    while ((line = in.readLine()) != null) {
22233                        if (line.contains("ignored: updated version")) continue;
22234                        pw.println(line);
22235                    }
22236                } catch (IOException ignored) {
22237                } finally {
22238                    IoUtils.closeQuietly(in);
22239                }
22240            }
22241
22242            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22243                BufferedReader in = null;
22244                String line = null;
22245                try {
22246                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22247                    while ((line = in.readLine()) != null) {
22248                        if (line.contains("ignored: updated version")) continue;
22249                        pw.print("msg,");
22250                        pw.println(line);
22251                    }
22252                } catch (IOException ignored) {
22253                } finally {
22254                    IoUtils.closeQuietly(in);
22255                }
22256            }
22257        }
22258
22259        // PackageInstaller should be called outside of mPackages lock
22260        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22261            // XXX should handle packageName != null by dumping only install data that
22262            // the given package is involved with.
22263            if (dumpState.onTitlePrinted()) pw.println();
22264            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22265        }
22266    }
22267
22268    private void dumpProto(FileDescriptor fd) {
22269        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22270
22271        synchronized (mPackages) {
22272            final long requiredVerifierPackageToken =
22273                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22274            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22275            proto.write(
22276                    PackageServiceDumpProto.PackageShortProto.UID,
22277                    getPackageUid(
22278                            mRequiredVerifierPackage,
22279                            MATCH_DEBUG_TRIAGED_MISSING,
22280                            UserHandle.USER_SYSTEM));
22281            proto.end(requiredVerifierPackageToken);
22282
22283            if (mIntentFilterVerifierComponent != null) {
22284                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22285                final long verifierPackageToken =
22286                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22287                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22288                proto.write(
22289                        PackageServiceDumpProto.PackageShortProto.UID,
22290                        getPackageUid(
22291                                verifierPackageName,
22292                                MATCH_DEBUG_TRIAGED_MISSING,
22293                                UserHandle.USER_SYSTEM));
22294                proto.end(verifierPackageToken);
22295            }
22296
22297            dumpSharedLibrariesProto(proto);
22298            dumpFeaturesProto(proto);
22299            mSettings.dumpPackagesProto(proto);
22300            mSettings.dumpSharedUsersProto(proto);
22301            dumpMessagesProto(proto);
22302        }
22303        proto.flush();
22304    }
22305
22306    private void dumpMessagesProto(ProtoOutputStream proto) {
22307        BufferedReader in = null;
22308        String line = null;
22309        try {
22310            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22311            while ((line = in.readLine()) != null) {
22312                if (line.contains("ignored: updated version")) continue;
22313                proto.write(PackageServiceDumpProto.MESSAGES, line);
22314            }
22315        } catch (IOException ignored) {
22316        } finally {
22317            IoUtils.closeQuietly(in);
22318        }
22319    }
22320
22321    private void dumpFeaturesProto(ProtoOutputStream proto) {
22322        synchronized (mAvailableFeatures) {
22323            final int count = mAvailableFeatures.size();
22324            for (int i = 0; i < count; i++) {
22325                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22326                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22327                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22328                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22329                proto.end(featureToken);
22330            }
22331        }
22332    }
22333
22334    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22335        final int count = mSharedLibraries.size();
22336        for (int i = 0; i < count; i++) {
22337            final String libName = mSharedLibraries.keyAt(i);
22338            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22339            if (versionedLib == null) {
22340                continue;
22341            }
22342            final int versionCount = versionedLib.size();
22343            for (int j = 0; j < versionCount; j++) {
22344                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22345                final long sharedLibraryToken =
22346                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22347                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22348                final boolean isJar = (libEntry.path != null);
22349                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22350                if (isJar) {
22351                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22352                } else {
22353                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22354                }
22355                proto.end(sharedLibraryToken);
22356            }
22357        }
22358    }
22359
22360    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22361        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22362        ipw.println();
22363        ipw.println("Dexopt state:");
22364        ipw.increaseIndent();
22365        Collection<PackageParser.Package> packages = null;
22366        if (packageName != null) {
22367            PackageParser.Package targetPackage = mPackages.get(packageName);
22368            if (targetPackage != null) {
22369                packages = Collections.singletonList(targetPackage);
22370            } else {
22371                ipw.println("Unable to find package: " + packageName);
22372                return;
22373            }
22374        } else {
22375            packages = mPackages.values();
22376        }
22377
22378        for (PackageParser.Package pkg : packages) {
22379            ipw.println("[" + pkg.packageName + "]");
22380            ipw.increaseIndent();
22381            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22382            ipw.decreaseIndent();
22383        }
22384    }
22385
22386    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22387        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22388        ipw.println();
22389        ipw.println("Compiler stats:");
22390        ipw.increaseIndent();
22391        Collection<PackageParser.Package> packages = null;
22392        if (packageName != null) {
22393            PackageParser.Package targetPackage = mPackages.get(packageName);
22394            if (targetPackage != null) {
22395                packages = Collections.singletonList(targetPackage);
22396            } else {
22397                ipw.println("Unable to find package: " + packageName);
22398                return;
22399            }
22400        } else {
22401            packages = mPackages.values();
22402        }
22403
22404        for (PackageParser.Package pkg : packages) {
22405            ipw.println("[" + pkg.packageName + "]");
22406            ipw.increaseIndent();
22407
22408            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22409            if (stats == null) {
22410                ipw.println("(No recorded stats)");
22411            } else {
22412                stats.dump(ipw);
22413            }
22414            ipw.decreaseIndent();
22415        }
22416    }
22417
22418    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
22419        pw.println("Enabled overlay paths:");
22420        final int N = mEnabledOverlayPaths.size();
22421        for (int i = 0; i < N; i++) {
22422            final int userId = mEnabledOverlayPaths.keyAt(i);
22423            pw.println(String.format("    User %d:", userId));
22424            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
22425                mEnabledOverlayPaths.valueAt(i);
22426            final int M = userSpecificOverlays.size();
22427            for (int j = 0; j < M; j++) {
22428                final String targetPackageName = userSpecificOverlays.keyAt(j);
22429                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
22430                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
22431            }
22432        }
22433    }
22434
22435    private String dumpDomainString(String packageName) {
22436        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22437                .getList();
22438        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22439
22440        ArraySet<String> result = new ArraySet<>();
22441        if (iviList.size() > 0) {
22442            for (IntentFilterVerificationInfo ivi : iviList) {
22443                for (String host : ivi.getDomains()) {
22444                    result.add(host);
22445                }
22446            }
22447        }
22448        if (filters != null && filters.size() > 0) {
22449            for (IntentFilter filter : filters) {
22450                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22451                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22452                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22453                    result.addAll(filter.getHostsList());
22454                }
22455            }
22456        }
22457
22458        StringBuilder sb = new StringBuilder(result.size() * 16);
22459        for (String domain : result) {
22460            if (sb.length() > 0) sb.append(" ");
22461            sb.append(domain);
22462        }
22463        return sb.toString();
22464    }
22465
22466    // ------- apps on sdcard specific code -------
22467    static final boolean DEBUG_SD_INSTALL = false;
22468
22469    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22470
22471    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22472
22473    private boolean mMediaMounted = false;
22474
22475    static String getEncryptKey() {
22476        try {
22477            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22478                    SD_ENCRYPTION_KEYSTORE_NAME);
22479            if (sdEncKey == null) {
22480                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22481                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22482                if (sdEncKey == null) {
22483                    Slog.e(TAG, "Failed to create encryption keys");
22484                    return null;
22485                }
22486            }
22487            return sdEncKey;
22488        } catch (NoSuchAlgorithmException nsae) {
22489            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22490            return null;
22491        } catch (IOException ioe) {
22492            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22493            return null;
22494        }
22495    }
22496
22497    /*
22498     * Update media status on PackageManager.
22499     */
22500    @Override
22501    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22502        enforceSystemOrRoot("Media status can only be updated by the system");
22503        // reader; this apparently protects mMediaMounted, but should probably
22504        // be a different lock in that case.
22505        synchronized (mPackages) {
22506            Log.i(TAG, "Updating external media status from "
22507                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22508                    + (mediaStatus ? "mounted" : "unmounted"));
22509            if (DEBUG_SD_INSTALL)
22510                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22511                        + ", mMediaMounted=" + mMediaMounted);
22512            if (mediaStatus == mMediaMounted) {
22513                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22514                        : 0, -1);
22515                mHandler.sendMessage(msg);
22516                return;
22517            }
22518            mMediaMounted = mediaStatus;
22519        }
22520        // Queue up an async operation since the package installation may take a
22521        // little while.
22522        mHandler.post(new Runnable() {
22523            public void run() {
22524                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22525            }
22526        });
22527    }
22528
22529    /**
22530     * Called by StorageManagerService when the initial ASECs to scan are available.
22531     * Should block until all the ASEC containers are finished being scanned.
22532     */
22533    public void scanAvailableAsecs() {
22534        updateExternalMediaStatusInner(true, false, false);
22535    }
22536
22537    /*
22538     * Collect information of applications on external media, map them against
22539     * existing containers and update information based on current mount status.
22540     * Please note that we always have to report status if reportStatus has been
22541     * set to true especially when unloading packages.
22542     */
22543    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22544            boolean externalStorage) {
22545        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22546        int[] uidArr = EmptyArray.INT;
22547
22548        final String[] list = PackageHelper.getSecureContainerList();
22549        if (ArrayUtils.isEmpty(list)) {
22550            Log.i(TAG, "No secure containers found");
22551        } else {
22552            // Process list of secure containers and categorize them
22553            // as active or stale based on their package internal state.
22554
22555            // reader
22556            synchronized (mPackages) {
22557                for (String cid : list) {
22558                    // Leave stages untouched for now; installer service owns them
22559                    if (PackageInstallerService.isStageName(cid)) continue;
22560
22561                    if (DEBUG_SD_INSTALL)
22562                        Log.i(TAG, "Processing container " + cid);
22563                    String pkgName = getAsecPackageName(cid);
22564                    if (pkgName == null) {
22565                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22566                        continue;
22567                    }
22568                    if (DEBUG_SD_INSTALL)
22569                        Log.i(TAG, "Looking for pkg : " + pkgName);
22570
22571                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22572                    if (ps == null) {
22573                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22574                        continue;
22575                    }
22576
22577                    /*
22578                     * Skip packages that are not external if we're unmounting
22579                     * external storage.
22580                     */
22581                    if (externalStorage && !isMounted && !isExternal(ps)) {
22582                        continue;
22583                    }
22584
22585                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22586                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22587                    // The package status is changed only if the code path
22588                    // matches between settings and the container id.
22589                    if (ps.codePathString != null
22590                            && ps.codePathString.startsWith(args.getCodePath())) {
22591                        if (DEBUG_SD_INSTALL) {
22592                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22593                                    + " at code path: " + ps.codePathString);
22594                        }
22595
22596                        // We do have a valid package installed on sdcard
22597                        processCids.put(args, ps.codePathString);
22598                        final int uid = ps.appId;
22599                        if (uid != -1) {
22600                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22601                        }
22602                    } else {
22603                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22604                                + ps.codePathString);
22605                    }
22606                }
22607            }
22608
22609            Arrays.sort(uidArr);
22610        }
22611
22612        // Process packages with valid entries.
22613        if (isMounted) {
22614            if (DEBUG_SD_INSTALL)
22615                Log.i(TAG, "Loading packages");
22616            loadMediaPackages(processCids, uidArr, externalStorage);
22617            startCleaningPackages();
22618            mInstallerService.onSecureContainersAvailable();
22619        } else {
22620            if (DEBUG_SD_INSTALL)
22621                Log.i(TAG, "Unloading packages");
22622            unloadMediaPackages(processCids, uidArr, reportStatus);
22623        }
22624    }
22625
22626    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22627            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22628        final int size = infos.size();
22629        final String[] packageNames = new String[size];
22630        final int[] packageUids = new int[size];
22631        for (int i = 0; i < size; i++) {
22632            final ApplicationInfo info = infos.get(i);
22633            packageNames[i] = info.packageName;
22634            packageUids[i] = info.uid;
22635        }
22636        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22637                finishedReceiver);
22638    }
22639
22640    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22641            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22642        sendResourcesChangedBroadcast(mediaStatus, replacing,
22643                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22644    }
22645
22646    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22647            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22648        int size = pkgList.length;
22649        if (size > 0) {
22650            // Send broadcasts here
22651            Bundle extras = new Bundle();
22652            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22653            if (uidArr != null) {
22654                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22655            }
22656            if (replacing) {
22657                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22658            }
22659            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22660                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22661            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22662        }
22663    }
22664
22665   /*
22666     * Look at potentially valid container ids from processCids If package
22667     * information doesn't match the one on record or package scanning fails,
22668     * the cid is added to list of removeCids. We currently don't delete stale
22669     * containers.
22670     */
22671    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22672            boolean externalStorage) {
22673        ArrayList<String> pkgList = new ArrayList<String>();
22674        Set<AsecInstallArgs> keys = processCids.keySet();
22675
22676        for (AsecInstallArgs args : keys) {
22677            String codePath = processCids.get(args);
22678            if (DEBUG_SD_INSTALL)
22679                Log.i(TAG, "Loading container : " + args.cid);
22680            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22681            try {
22682                // Make sure there are no container errors first.
22683                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22684                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22685                            + " when installing from sdcard");
22686                    continue;
22687                }
22688                // Check code path here.
22689                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22690                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22691                            + " does not match one in settings " + codePath);
22692                    continue;
22693                }
22694                // Parse package
22695                int parseFlags = mDefParseFlags;
22696                if (args.isExternalAsec()) {
22697                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22698                }
22699                if (args.isFwdLocked()) {
22700                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22701                }
22702
22703                synchronized (mInstallLock) {
22704                    PackageParser.Package pkg = null;
22705                    try {
22706                        // Sadly we don't know the package name yet to freeze it
22707                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22708                                SCAN_IGNORE_FROZEN, 0, null);
22709                    } catch (PackageManagerException e) {
22710                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22711                    }
22712                    // Scan the package
22713                    if (pkg != null) {
22714                        /*
22715                         * TODO why is the lock being held? doPostInstall is
22716                         * called in other places without the lock. This needs
22717                         * to be straightened out.
22718                         */
22719                        // writer
22720                        synchronized (mPackages) {
22721                            retCode = PackageManager.INSTALL_SUCCEEDED;
22722                            pkgList.add(pkg.packageName);
22723                            // Post process args
22724                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22725                                    pkg.applicationInfo.uid);
22726                        }
22727                    } else {
22728                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22729                    }
22730                }
22731
22732            } finally {
22733                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22734                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22735                }
22736            }
22737        }
22738        // writer
22739        synchronized (mPackages) {
22740            // If the platform SDK has changed since the last time we booted,
22741            // we need to re-grant app permission to catch any new ones that
22742            // appear. This is really a hack, and means that apps can in some
22743            // cases get permissions that the user didn't initially explicitly
22744            // allow... it would be nice to have some better way to handle
22745            // this situation.
22746            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22747                    : mSettings.getInternalVersion();
22748            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22749                    : StorageManager.UUID_PRIVATE_INTERNAL;
22750
22751            int updateFlags = UPDATE_PERMISSIONS_ALL;
22752            if (ver.sdkVersion != mSdkVersion) {
22753                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22754                        + mSdkVersion + "; regranting permissions for external");
22755                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22756            }
22757            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22758
22759            // Yay, everything is now upgraded
22760            ver.forceCurrent();
22761
22762            // can downgrade to reader
22763            // Persist settings
22764            mSettings.writeLPr();
22765        }
22766        // Send a broadcast to let everyone know we are done processing
22767        if (pkgList.size() > 0) {
22768            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22769        }
22770    }
22771
22772   /*
22773     * Utility method to unload a list of specified containers
22774     */
22775    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22776        // Just unmount all valid containers.
22777        for (AsecInstallArgs arg : cidArgs) {
22778            synchronized (mInstallLock) {
22779                arg.doPostDeleteLI(false);
22780           }
22781       }
22782   }
22783
22784    /*
22785     * Unload packages mounted on external media. This involves deleting package
22786     * data from internal structures, sending broadcasts about disabled packages,
22787     * gc'ing to free up references, unmounting all secure containers
22788     * corresponding to packages on external media, and posting a
22789     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22790     * that we always have to post this message if status has been requested no
22791     * matter what.
22792     */
22793    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22794            final boolean reportStatus) {
22795        if (DEBUG_SD_INSTALL)
22796            Log.i(TAG, "unloading media packages");
22797        ArrayList<String> pkgList = new ArrayList<String>();
22798        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22799        final Set<AsecInstallArgs> keys = processCids.keySet();
22800        for (AsecInstallArgs args : keys) {
22801            String pkgName = args.getPackageName();
22802            if (DEBUG_SD_INSTALL)
22803                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22804            // Delete package internally
22805            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22806            synchronized (mInstallLock) {
22807                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22808                final boolean res;
22809                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22810                        "unloadMediaPackages")) {
22811                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22812                            null);
22813                }
22814                if (res) {
22815                    pkgList.add(pkgName);
22816                } else {
22817                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22818                    failedList.add(args);
22819                }
22820            }
22821        }
22822
22823        // reader
22824        synchronized (mPackages) {
22825            // We didn't update the settings after removing each package;
22826            // write them now for all packages.
22827            mSettings.writeLPr();
22828        }
22829
22830        // We have to absolutely send UPDATED_MEDIA_STATUS only
22831        // after confirming that all the receivers processed the ordered
22832        // broadcast when packages get disabled, force a gc to clean things up.
22833        // and unload all the containers.
22834        if (pkgList.size() > 0) {
22835            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22836                    new IIntentReceiver.Stub() {
22837                public void performReceive(Intent intent, int resultCode, String data,
22838                        Bundle extras, boolean ordered, boolean sticky,
22839                        int sendingUser) throws RemoteException {
22840                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22841                            reportStatus ? 1 : 0, 1, keys);
22842                    mHandler.sendMessage(msg);
22843                }
22844            });
22845        } else {
22846            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22847                    keys);
22848            mHandler.sendMessage(msg);
22849        }
22850    }
22851
22852    private void loadPrivatePackages(final VolumeInfo vol) {
22853        mHandler.post(new Runnable() {
22854            @Override
22855            public void run() {
22856                loadPrivatePackagesInner(vol);
22857            }
22858        });
22859    }
22860
22861    private void loadPrivatePackagesInner(VolumeInfo vol) {
22862        final String volumeUuid = vol.fsUuid;
22863        if (TextUtils.isEmpty(volumeUuid)) {
22864            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22865            return;
22866        }
22867
22868        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22869        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22870        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22871
22872        final VersionInfo ver;
22873        final List<PackageSetting> packages;
22874        synchronized (mPackages) {
22875            ver = mSettings.findOrCreateVersion(volumeUuid);
22876            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22877        }
22878
22879        for (PackageSetting ps : packages) {
22880            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22881            synchronized (mInstallLock) {
22882                final PackageParser.Package pkg;
22883                try {
22884                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22885                    loaded.add(pkg.applicationInfo);
22886
22887                } catch (PackageManagerException e) {
22888                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22889                }
22890
22891                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22892                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22893                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22894                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22895                }
22896            }
22897        }
22898
22899        // Reconcile app data for all started/unlocked users
22900        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22901        final UserManager um = mContext.getSystemService(UserManager.class);
22902        UserManagerInternal umInternal = getUserManagerInternal();
22903        for (UserInfo user : um.getUsers()) {
22904            final int flags;
22905            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22906                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22907            } else if (umInternal.isUserRunning(user.id)) {
22908                flags = StorageManager.FLAG_STORAGE_DE;
22909            } else {
22910                continue;
22911            }
22912
22913            try {
22914                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22915                synchronized (mInstallLock) {
22916                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22917                }
22918            } catch (IllegalStateException e) {
22919                // Device was probably ejected, and we'll process that event momentarily
22920                Slog.w(TAG, "Failed to prepare storage: " + e);
22921            }
22922        }
22923
22924        synchronized (mPackages) {
22925            int updateFlags = UPDATE_PERMISSIONS_ALL;
22926            if (ver.sdkVersion != mSdkVersion) {
22927                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22928                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22929                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22930            }
22931            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22932
22933            // Yay, everything is now upgraded
22934            ver.forceCurrent();
22935
22936            mSettings.writeLPr();
22937        }
22938
22939        for (PackageFreezer freezer : freezers) {
22940            freezer.close();
22941        }
22942
22943        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22944        sendResourcesChangedBroadcast(true, false, loaded, null);
22945    }
22946
22947    private void unloadPrivatePackages(final VolumeInfo vol) {
22948        mHandler.post(new Runnable() {
22949            @Override
22950            public void run() {
22951                unloadPrivatePackagesInner(vol);
22952            }
22953        });
22954    }
22955
22956    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22957        final String volumeUuid = vol.fsUuid;
22958        if (TextUtils.isEmpty(volumeUuid)) {
22959            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22960            return;
22961        }
22962
22963        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22964        synchronized (mInstallLock) {
22965        synchronized (mPackages) {
22966            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22967            for (PackageSetting ps : packages) {
22968                if (ps.pkg == null) continue;
22969
22970                final ApplicationInfo info = ps.pkg.applicationInfo;
22971                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22972                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22973
22974                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22975                        "unloadPrivatePackagesInner")) {
22976                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22977                            false, null)) {
22978                        unloaded.add(info);
22979                    } else {
22980                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22981                    }
22982                }
22983
22984                // Try very hard to release any references to this package
22985                // so we don't risk the system server being killed due to
22986                // open FDs
22987                AttributeCache.instance().removePackage(ps.name);
22988            }
22989
22990            mSettings.writeLPr();
22991        }
22992        }
22993
22994        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22995        sendResourcesChangedBroadcast(false, false, unloaded, null);
22996
22997        // Try very hard to release any references to this path so we don't risk
22998        // the system server being killed due to open FDs
22999        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23000
23001        for (int i = 0; i < 3; i++) {
23002            System.gc();
23003            System.runFinalization();
23004        }
23005    }
23006
23007    private void assertPackageKnown(String volumeUuid, String packageName)
23008            throws PackageManagerException {
23009        synchronized (mPackages) {
23010            // Normalize package name to handle renamed packages
23011            packageName = normalizePackageNameLPr(packageName);
23012
23013            final PackageSetting ps = mSettings.mPackages.get(packageName);
23014            if (ps == null) {
23015                throw new PackageManagerException("Package " + packageName + " is unknown");
23016            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23017                throw new PackageManagerException(
23018                        "Package " + packageName + " found on unknown volume " + volumeUuid
23019                                + "; expected volume " + ps.volumeUuid);
23020            }
23021        }
23022    }
23023
23024    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23025            throws PackageManagerException {
23026        synchronized (mPackages) {
23027            // Normalize package name to handle renamed packages
23028            packageName = normalizePackageNameLPr(packageName);
23029
23030            final PackageSetting ps = mSettings.mPackages.get(packageName);
23031            if (ps == null) {
23032                throw new PackageManagerException("Package " + packageName + " is unknown");
23033            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23034                throw new PackageManagerException(
23035                        "Package " + packageName + " found on unknown volume " + volumeUuid
23036                                + "; expected volume " + ps.volumeUuid);
23037            } else if (!ps.getInstalled(userId)) {
23038                throw new PackageManagerException(
23039                        "Package " + packageName + " not installed for user " + userId);
23040            }
23041        }
23042    }
23043
23044    private List<String> collectAbsoluteCodePaths() {
23045        synchronized (mPackages) {
23046            List<String> codePaths = new ArrayList<>();
23047            final int packageCount = mSettings.mPackages.size();
23048            for (int i = 0; i < packageCount; i++) {
23049                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23050                codePaths.add(ps.codePath.getAbsolutePath());
23051            }
23052            return codePaths;
23053        }
23054    }
23055
23056    /**
23057     * Examine all apps present on given mounted volume, and destroy apps that
23058     * aren't expected, either due to uninstallation or reinstallation on
23059     * another volume.
23060     */
23061    private void reconcileApps(String volumeUuid) {
23062        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23063        List<File> filesToDelete = null;
23064
23065        final File[] files = FileUtils.listFilesOrEmpty(
23066                Environment.getDataAppDirectory(volumeUuid));
23067        for (File file : files) {
23068            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23069                    && !PackageInstallerService.isStageName(file.getName());
23070            if (!isPackage) {
23071                // Ignore entries which are not packages
23072                continue;
23073            }
23074
23075            String absolutePath = file.getAbsolutePath();
23076
23077            boolean pathValid = false;
23078            final int absoluteCodePathCount = absoluteCodePaths.size();
23079            for (int i = 0; i < absoluteCodePathCount; i++) {
23080                String absoluteCodePath = absoluteCodePaths.get(i);
23081                if (absolutePath.startsWith(absoluteCodePath)) {
23082                    pathValid = true;
23083                    break;
23084                }
23085            }
23086
23087            if (!pathValid) {
23088                if (filesToDelete == null) {
23089                    filesToDelete = new ArrayList<>();
23090                }
23091                filesToDelete.add(file);
23092            }
23093        }
23094
23095        if (filesToDelete != null) {
23096            final int fileToDeleteCount = filesToDelete.size();
23097            for (int i = 0; i < fileToDeleteCount; i++) {
23098                File fileToDelete = filesToDelete.get(i);
23099                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23100                synchronized (mInstallLock) {
23101                    removeCodePathLI(fileToDelete);
23102                }
23103            }
23104        }
23105    }
23106
23107    /**
23108     * Reconcile all app data for the given user.
23109     * <p>
23110     * Verifies that directories exist and that ownership and labeling is
23111     * correct for all installed apps on all mounted volumes.
23112     */
23113    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23114        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23115        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23116            final String volumeUuid = vol.getFsUuid();
23117            synchronized (mInstallLock) {
23118                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23119            }
23120        }
23121    }
23122
23123    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23124            boolean migrateAppData) {
23125        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23126    }
23127
23128    /**
23129     * Reconcile all app data on given mounted volume.
23130     * <p>
23131     * Destroys app data that isn't expected, either due to uninstallation or
23132     * reinstallation on another volume.
23133     * <p>
23134     * Verifies that directories exist and that ownership and labeling is
23135     * correct for all installed apps.
23136     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23137     */
23138    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23139            boolean migrateAppData, boolean onlyCoreApps) {
23140        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23141                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23142        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23143
23144        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23145        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23146
23147        // First look for stale data that doesn't belong, and check if things
23148        // have changed since we did our last restorecon
23149        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23150            if (StorageManager.isFileEncryptedNativeOrEmulated()
23151                    && !StorageManager.isUserKeyUnlocked(userId)) {
23152                throw new RuntimeException(
23153                        "Yikes, someone asked us to reconcile CE storage while " + userId
23154                                + " was still locked; this would have caused massive data loss!");
23155            }
23156
23157            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23158            for (File file : files) {
23159                final String packageName = file.getName();
23160                try {
23161                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23162                } catch (PackageManagerException e) {
23163                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23164                    try {
23165                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23166                                StorageManager.FLAG_STORAGE_CE, 0);
23167                    } catch (InstallerException e2) {
23168                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23169                    }
23170                }
23171            }
23172        }
23173        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23174            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23175            for (File file : files) {
23176                final String packageName = file.getName();
23177                try {
23178                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23179                } catch (PackageManagerException e) {
23180                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23181                    try {
23182                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23183                                StorageManager.FLAG_STORAGE_DE, 0);
23184                    } catch (InstallerException e2) {
23185                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23186                    }
23187                }
23188            }
23189        }
23190
23191        // Ensure that data directories are ready to roll for all packages
23192        // installed for this volume and user
23193        final List<PackageSetting> packages;
23194        synchronized (mPackages) {
23195            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23196        }
23197        int preparedCount = 0;
23198        for (PackageSetting ps : packages) {
23199            final String packageName = ps.name;
23200            if (ps.pkg == null) {
23201                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23202                // TODO: might be due to legacy ASEC apps; we should circle back
23203                // and reconcile again once they're scanned
23204                continue;
23205            }
23206            // Skip non-core apps if requested
23207            if (onlyCoreApps && !ps.pkg.coreApp) {
23208                result.add(packageName);
23209                continue;
23210            }
23211
23212            if (ps.getInstalled(userId)) {
23213                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23214                preparedCount++;
23215            }
23216        }
23217
23218        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23219        return result;
23220    }
23221
23222    /**
23223     * Prepare app data for the given app just after it was installed or
23224     * upgraded. This method carefully only touches users that it's installed
23225     * for, and it forces a restorecon to handle any seinfo changes.
23226     * <p>
23227     * Verifies that directories exist and that ownership and labeling is
23228     * correct for all installed apps. If there is an ownership mismatch, it
23229     * will try recovering system apps by wiping data; third-party app data is
23230     * left intact.
23231     * <p>
23232     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23233     */
23234    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23235        final PackageSetting ps;
23236        synchronized (mPackages) {
23237            ps = mSettings.mPackages.get(pkg.packageName);
23238            mSettings.writeKernelMappingLPr(ps);
23239        }
23240
23241        final UserManager um = mContext.getSystemService(UserManager.class);
23242        UserManagerInternal umInternal = getUserManagerInternal();
23243        for (UserInfo user : um.getUsers()) {
23244            final int flags;
23245            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23246                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23247            } else if (umInternal.isUserRunning(user.id)) {
23248                flags = StorageManager.FLAG_STORAGE_DE;
23249            } else {
23250                continue;
23251            }
23252
23253            if (ps.getInstalled(user.id)) {
23254                // TODO: when user data is locked, mark that we're still dirty
23255                prepareAppDataLIF(pkg, user.id, flags);
23256            }
23257        }
23258    }
23259
23260    /**
23261     * Prepare app data for the given app.
23262     * <p>
23263     * Verifies that directories exist and that ownership and labeling is
23264     * correct for all installed apps. If there is an ownership mismatch, this
23265     * will try recovering system apps by wiping data; third-party app data is
23266     * left intact.
23267     */
23268    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23269        if (pkg == null) {
23270            Slog.wtf(TAG, "Package was null!", new Throwable());
23271            return;
23272        }
23273        prepareAppDataLeafLIF(pkg, userId, flags);
23274        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23275        for (int i = 0; i < childCount; i++) {
23276            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23277        }
23278    }
23279
23280    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23281            boolean maybeMigrateAppData) {
23282        prepareAppDataLIF(pkg, userId, flags);
23283
23284        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23285            // We may have just shuffled around app data directories, so
23286            // prepare them one more time
23287            prepareAppDataLIF(pkg, userId, flags);
23288        }
23289    }
23290
23291    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23292        if (DEBUG_APP_DATA) {
23293            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23294                    + Integer.toHexString(flags));
23295        }
23296
23297        final String volumeUuid = pkg.volumeUuid;
23298        final String packageName = pkg.packageName;
23299        final ApplicationInfo app = pkg.applicationInfo;
23300        final int appId = UserHandle.getAppId(app.uid);
23301
23302        Preconditions.checkNotNull(app.seInfo);
23303
23304        long ceDataInode = -1;
23305        try {
23306            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23307                    appId, app.seInfo, app.targetSdkVersion);
23308        } catch (InstallerException e) {
23309            if (app.isSystemApp()) {
23310                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23311                        + ", but trying to recover: " + e);
23312                destroyAppDataLeafLIF(pkg, userId, flags);
23313                try {
23314                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23315                            appId, app.seInfo, app.targetSdkVersion);
23316                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23317                } catch (InstallerException e2) {
23318                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23319                }
23320            } else {
23321                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23322            }
23323        }
23324
23325        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23326            // TODO: mark this structure as dirty so we persist it!
23327            synchronized (mPackages) {
23328                final PackageSetting ps = mSettings.mPackages.get(packageName);
23329                if (ps != null) {
23330                    ps.setCeDataInode(ceDataInode, userId);
23331                }
23332            }
23333        }
23334
23335        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23336    }
23337
23338    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23339        if (pkg == null) {
23340            Slog.wtf(TAG, "Package was null!", new Throwable());
23341            return;
23342        }
23343        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23344        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23345        for (int i = 0; i < childCount; i++) {
23346            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23347        }
23348    }
23349
23350    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23351        final String volumeUuid = pkg.volumeUuid;
23352        final String packageName = pkg.packageName;
23353        final ApplicationInfo app = pkg.applicationInfo;
23354
23355        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23356            // Create a native library symlink only if we have native libraries
23357            // and if the native libraries are 32 bit libraries. We do not provide
23358            // this symlink for 64 bit libraries.
23359            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23360                final String nativeLibPath = app.nativeLibraryDir;
23361                try {
23362                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23363                            nativeLibPath, userId);
23364                } catch (InstallerException e) {
23365                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23366                }
23367            }
23368        }
23369    }
23370
23371    /**
23372     * For system apps on non-FBE devices, this method migrates any existing
23373     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23374     * requested by the app.
23375     */
23376    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23377        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23378                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23379            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23380                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23381            try {
23382                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23383                        storageTarget);
23384            } catch (InstallerException e) {
23385                logCriticalInfo(Log.WARN,
23386                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23387            }
23388            return true;
23389        } else {
23390            return false;
23391        }
23392    }
23393
23394    public PackageFreezer freezePackage(String packageName, String killReason) {
23395        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23396    }
23397
23398    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23399        return new PackageFreezer(packageName, userId, killReason);
23400    }
23401
23402    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23403            String killReason) {
23404        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23405    }
23406
23407    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23408            String killReason) {
23409        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23410            return new PackageFreezer();
23411        } else {
23412            return freezePackage(packageName, userId, killReason);
23413        }
23414    }
23415
23416    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23417            String killReason) {
23418        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23419    }
23420
23421    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23422            String killReason) {
23423        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23424            return new PackageFreezer();
23425        } else {
23426            return freezePackage(packageName, userId, killReason);
23427        }
23428    }
23429
23430    /**
23431     * Class that freezes and kills the given package upon creation, and
23432     * unfreezes it upon closing. This is typically used when doing surgery on
23433     * app code/data to prevent the app from running while you're working.
23434     */
23435    private class PackageFreezer implements AutoCloseable {
23436        private final String mPackageName;
23437        private final PackageFreezer[] mChildren;
23438
23439        private final boolean mWeFroze;
23440
23441        private final AtomicBoolean mClosed = new AtomicBoolean();
23442        private final CloseGuard mCloseGuard = CloseGuard.get();
23443
23444        /**
23445         * Create and return a stub freezer that doesn't actually do anything,
23446         * typically used when someone requested
23447         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23448         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23449         */
23450        public PackageFreezer() {
23451            mPackageName = null;
23452            mChildren = null;
23453            mWeFroze = false;
23454            mCloseGuard.open("close");
23455        }
23456
23457        public PackageFreezer(String packageName, int userId, String killReason) {
23458            synchronized (mPackages) {
23459                mPackageName = packageName;
23460                mWeFroze = mFrozenPackages.add(mPackageName);
23461
23462                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23463                if (ps != null) {
23464                    killApplication(ps.name, ps.appId, userId, killReason);
23465                }
23466
23467                final PackageParser.Package p = mPackages.get(packageName);
23468                if (p != null && p.childPackages != null) {
23469                    final int N = p.childPackages.size();
23470                    mChildren = new PackageFreezer[N];
23471                    for (int i = 0; i < N; i++) {
23472                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23473                                userId, killReason);
23474                    }
23475                } else {
23476                    mChildren = null;
23477                }
23478            }
23479            mCloseGuard.open("close");
23480        }
23481
23482        @Override
23483        protected void finalize() throws Throwable {
23484            try {
23485                mCloseGuard.warnIfOpen();
23486                close();
23487            } finally {
23488                super.finalize();
23489            }
23490        }
23491
23492        @Override
23493        public void close() {
23494            mCloseGuard.close();
23495            if (mClosed.compareAndSet(false, true)) {
23496                synchronized (mPackages) {
23497                    if (mWeFroze) {
23498                        mFrozenPackages.remove(mPackageName);
23499                    }
23500
23501                    if (mChildren != null) {
23502                        for (PackageFreezer freezer : mChildren) {
23503                            freezer.close();
23504                        }
23505                    }
23506                }
23507            }
23508        }
23509    }
23510
23511    /**
23512     * Verify that given package is currently frozen.
23513     */
23514    private void checkPackageFrozen(String packageName) {
23515        synchronized (mPackages) {
23516            if (!mFrozenPackages.contains(packageName)) {
23517                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23518            }
23519        }
23520    }
23521
23522    @Override
23523    public int movePackage(final String packageName, final String volumeUuid) {
23524        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23525
23526        final int callingUid = Binder.getCallingUid();
23527        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23528        final int moveId = mNextMoveId.getAndIncrement();
23529        mHandler.post(new Runnable() {
23530            @Override
23531            public void run() {
23532                try {
23533                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23534                } catch (PackageManagerException e) {
23535                    Slog.w(TAG, "Failed to move " + packageName, e);
23536                    mMoveCallbacks.notifyStatusChanged(moveId,
23537                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23538                }
23539            }
23540        });
23541        return moveId;
23542    }
23543
23544    private void movePackageInternal(final String packageName, final String volumeUuid,
23545            final int moveId, final int callingUid, UserHandle user)
23546                    throws PackageManagerException {
23547        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23548        final PackageManager pm = mContext.getPackageManager();
23549
23550        final boolean currentAsec;
23551        final String currentVolumeUuid;
23552        final File codeFile;
23553        final String installerPackageName;
23554        final String packageAbiOverride;
23555        final int appId;
23556        final String seinfo;
23557        final String label;
23558        final int targetSdkVersion;
23559        final PackageFreezer freezer;
23560        final int[] installedUserIds;
23561
23562        // reader
23563        synchronized (mPackages) {
23564            final PackageParser.Package pkg = mPackages.get(packageName);
23565            final PackageSetting ps = mSettings.mPackages.get(packageName);
23566            if (pkg == null
23567                    || ps == null
23568                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23569                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23570            }
23571            if (pkg.applicationInfo.isSystemApp()) {
23572                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23573                        "Cannot move system application");
23574            }
23575
23576            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23577            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23578                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23579            if (isInternalStorage && !allow3rdPartyOnInternal) {
23580                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23581                        "3rd party apps are not allowed on internal storage");
23582            }
23583
23584            if (pkg.applicationInfo.isExternalAsec()) {
23585                currentAsec = true;
23586                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23587            } else if (pkg.applicationInfo.isForwardLocked()) {
23588                currentAsec = true;
23589                currentVolumeUuid = "forward_locked";
23590            } else {
23591                currentAsec = false;
23592                currentVolumeUuid = ps.volumeUuid;
23593
23594                final File probe = new File(pkg.codePath);
23595                final File probeOat = new File(probe, "oat");
23596                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23597                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23598                            "Move only supported for modern cluster style installs");
23599                }
23600            }
23601
23602            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23603                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23604                        "Package already moved to " + volumeUuid);
23605            }
23606            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23607                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23608                        "Device admin cannot be moved");
23609            }
23610
23611            if (mFrozenPackages.contains(packageName)) {
23612                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23613                        "Failed to move already frozen package");
23614            }
23615
23616            codeFile = new File(pkg.codePath);
23617            installerPackageName = ps.installerPackageName;
23618            packageAbiOverride = ps.cpuAbiOverrideString;
23619            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23620            seinfo = pkg.applicationInfo.seInfo;
23621            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23622            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23623            freezer = freezePackage(packageName, "movePackageInternal");
23624            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23625        }
23626
23627        final Bundle extras = new Bundle();
23628        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23629        extras.putString(Intent.EXTRA_TITLE, label);
23630        mMoveCallbacks.notifyCreated(moveId, extras);
23631
23632        int installFlags;
23633        final boolean moveCompleteApp;
23634        final File measurePath;
23635
23636        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23637            installFlags = INSTALL_INTERNAL;
23638            moveCompleteApp = !currentAsec;
23639            measurePath = Environment.getDataAppDirectory(volumeUuid);
23640        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23641            installFlags = INSTALL_EXTERNAL;
23642            moveCompleteApp = false;
23643            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23644        } else {
23645            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23646            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23647                    || !volume.isMountedWritable()) {
23648                freezer.close();
23649                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23650                        "Move location not mounted private volume");
23651            }
23652
23653            Preconditions.checkState(!currentAsec);
23654
23655            installFlags = INSTALL_INTERNAL;
23656            moveCompleteApp = true;
23657            measurePath = Environment.getDataAppDirectory(volumeUuid);
23658        }
23659
23660        final PackageStats stats = new PackageStats(null, -1);
23661        synchronized (mInstaller) {
23662            for (int userId : installedUserIds) {
23663                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23664                    freezer.close();
23665                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23666                            "Failed to measure package size");
23667                }
23668            }
23669        }
23670
23671        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23672                + stats.dataSize);
23673
23674        final long startFreeBytes = measurePath.getUsableSpace();
23675        final long sizeBytes;
23676        if (moveCompleteApp) {
23677            sizeBytes = stats.codeSize + stats.dataSize;
23678        } else {
23679            sizeBytes = stats.codeSize;
23680        }
23681
23682        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23683            freezer.close();
23684            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23685                    "Not enough free space to move");
23686        }
23687
23688        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23689
23690        final CountDownLatch installedLatch = new CountDownLatch(1);
23691        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23692            @Override
23693            public void onUserActionRequired(Intent intent) throws RemoteException {
23694                throw new IllegalStateException();
23695            }
23696
23697            @Override
23698            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23699                    Bundle extras) throws RemoteException {
23700                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23701                        + PackageManager.installStatusToString(returnCode, msg));
23702
23703                installedLatch.countDown();
23704                freezer.close();
23705
23706                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23707                switch (status) {
23708                    case PackageInstaller.STATUS_SUCCESS:
23709                        mMoveCallbacks.notifyStatusChanged(moveId,
23710                                PackageManager.MOVE_SUCCEEDED);
23711                        break;
23712                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23713                        mMoveCallbacks.notifyStatusChanged(moveId,
23714                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23715                        break;
23716                    default:
23717                        mMoveCallbacks.notifyStatusChanged(moveId,
23718                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23719                        break;
23720                }
23721            }
23722        };
23723
23724        final MoveInfo move;
23725        if (moveCompleteApp) {
23726            // Kick off a thread to report progress estimates
23727            new Thread() {
23728                @Override
23729                public void run() {
23730                    while (true) {
23731                        try {
23732                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23733                                break;
23734                            }
23735                        } catch (InterruptedException ignored) {
23736                        }
23737
23738                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23739                        final int progress = 10 + (int) MathUtils.constrain(
23740                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23741                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23742                    }
23743                }
23744            }.start();
23745
23746            final String dataAppName = codeFile.getName();
23747            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23748                    dataAppName, appId, seinfo, targetSdkVersion);
23749        } else {
23750            move = null;
23751        }
23752
23753        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23754
23755        final Message msg = mHandler.obtainMessage(INIT_COPY);
23756        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23757        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23758                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23759                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23760                PackageManager.INSTALL_REASON_UNKNOWN);
23761        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23762        msg.obj = params;
23763
23764        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23765                System.identityHashCode(msg.obj));
23766        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23767                System.identityHashCode(msg.obj));
23768
23769        mHandler.sendMessage(msg);
23770    }
23771
23772    @Override
23773    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23774        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23775
23776        final int realMoveId = mNextMoveId.getAndIncrement();
23777        final Bundle extras = new Bundle();
23778        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23779        mMoveCallbacks.notifyCreated(realMoveId, extras);
23780
23781        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23782            @Override
23783            public void onCreated(int moveId, Bundle extras) {
23784                // Ignored
23785            }
23786
23787            @Override
23788            public void onStatusChanged(int moveId, int status, long estMillis) {
23789                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23790            }
23791        };
23792
23793        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23794        storage.setPrimaryStorageUuid(volumeUuid, callback);
23795        return realMoveId;
23796    }
23797
23798    @Override
23799    public int getMoveStatus(int moveId) {
23800        mContext.enforceCallingOrSelfPermission(
23801                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23802        return mMoveCallbacks.mLastStatus.get(moveId);
23803    }
23804
23805    @Override
23806    public void registerMoveCallback(IPackageMoveObserver callback) {
23807        mContext.enforceCallingOrSelfPermission(
23808                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23809        mMoveCallbacks.register(callback);
23810    }
23811
23812    @Override
23813    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23814        mContext.enforceCallingOrSelfPermission(
23815                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23816        mMoveCallbacks.unregister(callback);
23817    }
23818
23819    @Override
23820    public boolean setInstallLocation(int loc) {
23821        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23822                null);
23823        if (getInstallLocation() == loc) {
23824            return true;
23825        }
23826        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23827                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23828            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23829                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23830            return true;
23831        }
23832        return false;
23833   }
23834
23835    @Override
23836    public int getInstallLocation() {
23837        // allow instant app access
23838        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23839                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23840                PackageHelper.APP_INSTALL_AUTO);
23841    }
23842
23843    /** Called by UserManagerService */
23844    void cleanUpUser(UserManagerService userManager, int userHandle) {
23845        synchronized (mPackages) {
23846            mDirtyUsers.remove(userHandle);
23847            mUserNeedsBadging.delete(userHandle);
23848            mSettings.removeUserLPw(userHandle);
23849            mPendingBroadcasts.remove(userHandle);
23850            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23851            removeUnusedPackagesLPw(userManager, userHandle);
23852        }
23853    }
23854
23855    /**
23856     * We're removing userHandle and would like to remove any downloaded packages
23857     * that are no longer in use by any other user.
23858     * @param userHandle the user being removed
23859     */
23860    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23861        final boolean DEBUG_CLEAN_APKS = false;
23862        int [] users = userManager.getUserIds();
23863        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23864        while (psit.hasNext()) {
23865            PackageSetting ps = psit.next();
23866            if (ps.pkg == null) {
23867                continue;
23868            }
23869            final String packageName = ps.pkg.packageName;
23870            // Skip over if system app
23871            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23872                continue;
23873            }
23874            if (DEBUG_CLEAN_APKS) {
23875                Slog.i(TAG, "Checking package " + packageName);
23876            }
23877            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23878            if (keep) {
23879                if (DEBUG_CLEAN_APKS) {
23880                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23881                }
23882            } else {
23883                for (int i = 0; i < users.length; i++) {
23884                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23885                        keep = true;
23886                        if (DEBUG_CLEAN_APKS) {
23887                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23888                                    + users[i]);
23889                        }
23890                        break;
23891                    }
23892                }
23893            }
23894            if (!keep) {
23895                if (DEBUG_CLEAN_APKS) {
23896                    Slog.i(TAG, "  Removing package " + packageName);
23897                }
23898                mHandler.post(new Runnable() {
23899                    public void run() {
23900                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23901                                userHandle, 0);
23902                    } //end run
23903                });
23904            }
23905        }
23906    }
23907
23908    /** Called by UserManagerService */
23909    void createNewUser(int userId, String[] disallowedPackages) {
23910        synchronized (mInstallLock) {
23911            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23912        }
23913        synchronized (mPackages) {
23914            scheduleWritePackageRestrictionsLocked(userId);
23915            scheduleWritePackageListLocked(userId);
23916            applyFactoryDefaultBrowserLPw(userId);
23917            primeDomainVerificationsLPw(userId);
23918        }
23919    }
23920
23921    void onNewUserCreated(final int userId) {
23922        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23923        // If permission review for legacy apps is required, we represent
23924        // dagerous permissions for such apps as always granted runtime
23925        // permissions to keep per user flag state whether review is needed.
23926        // Hence, if a new user is added we have to propagate dangerous
23927        // permission grants for these legacy apps.
23928        if (mPermissionReviewRequired) {
23929            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23930                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23931        }
23932    }
23933
23934    @Override
23935    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23936        mContext.enforceCallingOrSelfPermission(
23937                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23938                "Only package verification agents can read the verifier device identity");
23939
23940        synchronized (mPackages) {
23941            return mSettings.getVerifierDeviceIdentityLPw();
23942        }
23943    }
23944
23945    @Override
23946    public void setPermissionEnforced(String permission, boolean enforced) {
23947        // TODO: Now that we no longer change GID for storage, this should to away.
23948        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23949                "setPermissionEnforced");
23950        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23951            synchronized (mPackages) {
23952                if (mSettings.mReadExternalStorageEnforced == null
23953                        || mSettings.mReadExternalStorageEnforced != enforced) {
23954                    mSettings.mReadExternalStorageEnforced = enforced;
23955                    mSettings.writeLPr();
23956                }
23957            }
23958            // kill any non-foreground processes so we restart them and
23959            // grant/revoke the GID.
23960            final IActivityManager am = ActivityManager.getService();
23961            if (am != null) {
23962                final long token = Binder.clearCallingIdentity();
23963                try {
23964                    am.killProcessesBelowForeground("setPermissionEnforcement");
23965                } catch (RemoteException e) {
23966                } finally {
23967                    Binder.restoreCallingIdentity(token);
23968                }
23969            }
23970        } else {
23971            throw new IllegalArgumentException("No selective enforcement for " + permission);
23972        }
23973    }
23974
23975    @Override
23976    @Deprecated
23977    public boolean isPermissionEnforced(String permission) {
23978        // allow instant applications
23979        return true;
23980    }
23981
23982    @Override
23983    public boolean isStorageLow() {
23984        // allow instant applications
23985        final long token = Binder.clearCallingIdentity();
23986        try {
23987            final DeviceStorageMonitorInternal
23988                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23989            if (dsm != null) {
23990                return dsm.isMemoryLow();
23991            } else {
23992                return false;
23993            }
23994        } finally {
23995            Binder.restoreCallingIdentity(token);
23996        }
23997    }
23998
23999    @Override
24000    public IPackageInstaller getPackageInstaller() {
24001        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24002            return null;
24003        }
24004        return mInstallerService;
24005    }
24006
24007    private boolean userNeedsBadging(int userId) {
24008        int index = mUserNeedsBadging.indexOfKey(userId);
24009        if (index < 0) {
24010            final UserInfo userInfo;
24011            final long token = Binder.clearCallingIdentity();
24012            try {
24013                userInfo = sUserManager.getUserInfo(userId);
24014            } finally {
24015                Binder.restoreCallingIdentity(token);
24016            }
24017            final boolean b;
24018            if (userInfo != null && userInfo.isManagedProfile()) {
24019                b = true;
24020            } else {
24021                b = false;
24022            }
24023            mUserNeedsBadging.put(userId, b);
24024            return b;
24025        }
24026        return mUserNeedsBadging.valueAt(index);
24027    }
24028
24029    @Override
24030    public KeySet getKeySetByAlias(String packageName, String alias) {
24031        if (packageName == null || alias == null) {
24032            return null;
24033        }
24034        synchronized(mPackages) {
24035            final PackageParser.Package pkg = mPackages.get(packageName);
24036            if (pkg == null) {
24037                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24038                throw new IllegalArgumentException("Unknown package: " + packageName);
24039            }
24040            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24041            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24042                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24043                throw new IllegalArgumentException("Unknown package: " + packageName);
24044            }
24045            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24046            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24047        }
24048    }
24049
24050    @Override
24051    public KeySet getSigningKeySet(String packageName) {
24052        if (packageName == null) {
24053            return null;
24054        }
24055        synchronized(mPackages) {
24056            final int callingUid = Binder.getCallingUid();
24057            final int callingUserId = UserHandle.getUserId(callingUid);
24058            final PackageParser.Package pkg = mPackages.get(packageName);
24059            if (pkg == null) {
24060                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24061                throw new IllegalArgumentException("Unknown package: " + packageName);
24062            }
24063            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24064            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24065                // filter and pretend the package doesn't exist
24066                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24067                        + ", uid:" + callingUid);
24068                throw new IllegalArgumentException("Unknown package: " + packageName);
24069            }
24070            if (pkg.applicationInfo.uid != callingUid
24071                    && Process.SYSTEM_UID != callingUid) {
24072                throw new SecurityException("May not access signing KeySet of other apps.");
24073            }
24074            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24075            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24076        }
24077    }
24078
24079    @Override
24080    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24081        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24082            return false;
24083        }
24084        if (packageName == null || ks == null) {
24085            return false;
24086        }
24087        synchronized(mPackages) {
24088            final PackageParser.Package pkg = mPackages.get(packageName);
24089            if (pkg == null) {
24090                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24091                throw new IllegalArgumentException("Unknown package: " + packageName);
24092            }
24093            IBinder ksh = ks.getToken();
24094            if (ksh instanceof KeySetHandle) {
24095                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24096                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24097            }
24098            return false;
24099        }
24100    }
24101
24102    @Override
24103    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24104        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24105            return false;
24106        }
24107        if (packageName == null || ks == null) {
24108            return false;
24109        }
24110        synchronized(mPackages) {
24111            final PackageParser.Package pkg = mPackages.get(packageName);
24112            if (pkg == null) {
24113                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24114                throw new IllegalArgumentException("Unknown package: " + packageName);
24115            }
24116            IBinder ksh = ks.getToken();
24117            if (ksh instanceof KeySetHandle) {
24118                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24119                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24120            }
24121            return false;
24122        }
24123    }
24124
24125    private void deletePackageIfUnusedLPr(final String packageName) {
24126        PackageSetting ps = mSettings.mPackages.get(packageName);
24127        if (ps == null) {
24128            return;
24129        }
24130        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24131            // TODO Implement atomic delete if package is unused
24132            // It is currently possible that the package will be deleted even if it is installed
24133            // after this method returns.
24134            mHandler.post(new Runnable() {
24135                public void run() {
24136                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24137                            0, PackageManager.DELETE_ALL_USERS);
24138                }
24139            });
24140        }
24141    }
24142
24143    /**
24144     * Check and throw if the given before/after packages would be considered a
24145     * downgrade.
24146     */
24147    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24148            throws PackageManagerException {
24149        if (after.versionCode < before.mVersionCode) {
24150            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24151                    "Update version code " + after.versionCode + " is older than current "
24152                    + before.mVersionCode);
24153        } else if (after.versionCode == before.mVersionCode) {
24154            if (after.baseRevisionCode < before.baseRevisionCode) {
24155                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24156                        "Update base revision code " + after.baseRevisionCode
24157                        + " is older than current " + before.baseRevisionCode);
24158            }
24159
24160            if (!ArrayUtils.isEmpty(after.splitNames)) {
24161                for (int i = 0; i < after.splitNames.length; i++) {
24162                    final String splitName = after.splitNames[i];
24163                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24164                    if (j != -1) {
24165                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24166                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24167                                    "Update split " + splitName + " revision code "
24168                                    + after.splitRevisionCodes[i] + " is older than current "
24169                                    + before.splitRevisionCodes[j]);
24170                        }
24171                    }
24172                }
24173            }
24174        }
24175    }
24176
24177    private static class MoveCallbacks extends Handler {
24178        private static final int MSG_CREATED = 1;
24179        private static final int MSG_STATUS_CHANGED = 2;
24180
24181        private final RemoteCallbackList<IPackageMoveObserver>
24182                mCallbacks = new RemoteCallbackList<>();
24183
24184        private final SparseIntArray mLastStatus = new SparseIntArray();
24185
24186        public MoveCallbacks(Looper looper) {
24187            super(looper);
24188        }
24189
24190        public void register(IPackageMoveObserver callback) {
24191            mCallbacks.register(callback);
24192        }
24193
24194        public void unregister(IPackageMoveObserver callback) {
24195            mCallbacks.unregister(callback);
24196        }
24197
24198        @Override
24199        public void handleMessage(Message msg) {
24200            final SomeArgs args = (SomeArgs) msg.obj;
24201            final int n = mCallbacks.beginBroadcast();
24202            for (int i = 0; i < n; i++) {
24203                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24204                try {
24205                    invokeCallback(callback, msg.what, args);
24206                } catch (RemoteException ignored) {
24207                }
24208            }
24209            mCallbacks.finishBroadcast();
24210            args.recycle();
24211        }
24212
24213        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24214                throws RemoteException {
24215            switch (what) {
24216                case MSG_CREATED: {
24217                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24218                    break;
24219                }
24220                case MSG_STATUS_CHANGED: {
24221                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24222                    break;
24223                }
24224            }
24225        }
24226
24227        private void notifyCreated(int moveId, Bundle extras) {
24228            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24229
24230            final SomeArgs args = SomeArgs.obtain();
24231            args.argi1 = moveId;
24232            args.arg2 = extras;
24233            obtainMessage(MSG_CREATED, args).sendToTarget();
24234        }
24235
24236        private void notifyStatusChanged(int moveId, int status) {
24237            notifyStatusChanged(moveId, status, -1);
24238        }
24239
24240        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24241            Slog.v(TAG, "Move " + moveId + " status " + status);
24242
24243            final SomeArgs args = SomeArgs.obtain();
24244            args.argi1 = moveId;
24245            args.argi2 = status;
24246            args.arg3 = estMillis;
24247            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24248
24249            synchronized (mLastStatus) {
24250                mLastStatus.put(moveId, status);
24251            }
24252        }
24253    }
24254
24255    private final static class OnPermissionChangeListeners extends Handler {
24256        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24257
24258        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24259                new RemoteCallbackList<>();
24260
24261        public OnPermissionChangeListeners(Looper looper) {
24262            super(looper);
24263        }
24264
24265        @Override
24266        public void handleMessage(Message msg) {
24267            switch (msg.what) {
24268                case MSG_ON_PERMISSIONS_CHANGED: {
24269                    final int uid = msg.arg1;
24270                    handleOnPermissionsChanged(uid);
24271                } break;
24272            }
24273        }
24274
24275        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24276            mPermissionListeners.register(listener);
24277
24278        }
24279
24280        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24281            mPermissionListeners.unregister(listener);
24282        }
24283
24284        public void onPermissionsChanged(int uid) {
24285            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24286                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24287            }
24288        }
24289
24290        private void handleOnPermissionsChanged(int uid) {
24291            final int count = mPermissionListeners.beginBroadcast();
24292            try {
24293                for (int i = 0; i < count; i++) {
24294                    IOnPermissionsChangeListener callback = mPermissionListeners
24295                            .getBroadcastItem(i);
24296                    try {
24297                        callback.onPermissionsChanged(uid);
24298                    } catch (RemoteException e) {
24299                        Log.e(TAG, "Permission listener is dead", e);
24300                    }
24301                }
24302            } finally {
24303                mPermissionListeners.finishBroadcast();
24304            }
24305        }
24306    }
24307
24308    private class PackageManagerInternalImpl extends PackageManagerInternal {
24309        @Override
24310        public void setLocationPackagesProvider(PackagesProvider provider) {
24311            synchronized (mPackages) {
24312                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24313            }
24314        }
24315
24316        @Override
24317        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24318            synchronized (mPackages) {
24319                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24320            }
24321        }
24322
24323        @Override
24324        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24325            synchronized (mPackages) {
24326                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24327            }
24328        }
24329
24330        @Override
24331        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24332            synchronized (mPackages) {
24333                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24334            }
24335        }
24336
24337        @Override
24338        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24339            synchronized (mPackages) {
24340                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24341            }
24342        }
24343
24344        @Override
24345        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24346            synchronized (mPackages) {
24347                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24348            }
24349        }
24350
24351        @Override
24352        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24353            synchronized (mPackages) {
24354                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24355                        packageName, userId);
24356            }
24357        }
24358
24359        @Override
24360        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24361            synchronized (mPackages) {
24362                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24363                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24364                        packageName, userId);
24365            }
24366        }
24367
24368        @Override
24369        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24370            synchronized (mPackages) {
24371                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24372                        packageName, userId);
24373            }
24374        }
24375
24376        @Override
24377        public void setKeepUninstalledPackages(final List<String> packageList) {
24378            Preconditions.checkNotNull(packageList);
24379            List<String> removedFromList = null;
24380            synchronized (mPackages) {
24381                if (mKeepUninstalledPackages != null) {
24382                    final int packagesCount = mKeepUninstalledPackages.size();
24383                    for (int i = 0; i < packagesCount; i++) {
24384                        String oldPackage = mKeepUninstalledPackages.get(i);
24385                        if (packageList != null && packageList.contains(oldPackage)) {
24386                            continue;
24387                        }
24388                        if (removedFromList == null) {
24389                            removedFromList = new ArrayList<>();
24390                        }
24391                        removedFromList.add(oldPackage);
24392                    }
24393                }
24394                mKeepUninstalledPackages = new ArrayList<>(packageList);
24395                if (removedFromList != null) {
24396                    final int removedCount = removedFromList.size();
24397                    for (int i = 0; i < removedCount; i++) {
24398                        deletePackageIfUnusedLPr(removedFromList.get(i));
24399                    }
24400                }
24401            }
24402        }
24403
24404        @Override
24405        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24406            synchronized (mPackages) {
24407                // If we do not support permission review, done.
24408                if (!mPermissionReviewRequired) {
24409                    return false;
24410                }
24411
24412                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24413                if (packageSetting == null) {
24414                    return false;
24415                }
24416
24417                // Permission review applies only to apps not supporting the new permission model.
24418                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24419                    return false;
24420                }
24421
24422                // Legacy apps have the permission and get user consent on launch.
24423                PermissionsState permissionsState = packageSetting.getPermissionsState();
24424                return permissionsState.isPermissionReviewRequired(userId);
24425            }
24426        }
24427
24428        @Override
24429        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
24430            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
24431        }
24432
24433        @Override
24434        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24435                int userId) {
24436            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24437        }
24438
24439        @Override
24440        public void setDeviceAndProfileOwnerPackages(
24441                int deviceOwnerUserId, String deviceOwnerPackage,
24442                SparseArray<String> profileOwnerPackages) {
24443            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24444                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24445        }
24446
24447        @Override
24448        public boolean isPackageDataProtected(int userId, String packageName) {
24449            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24450        }
24451
24452        @Override
24453        public boolean isPackageEphemeral(int userId, String packageName) {
24454            synchronized (mPackages) {
24455                final PackageSetting ps = mSettings.mPackages.get(packageName);
24456                return ps != null ? ps.getInstantApp(userId) : false;
24457            }
24458        }
24459
24460        @Override
24461        public boolean wasPackageEverLaunched(String packageName, int userId) {
24462            synchronized (mPackages) {
24463                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24464            }
24465        }
24466
24467        @Override
24468        public void grantRuntimePermission(String packageName, String name, int userId,
24469                boolean overridePolicy) {
24470            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24471                    overridePolicy);
24472        }
24473
24474        @Override
24475        public void revokeRuntimePermission(String packageName, String name, int userId,
24476                boolean overridePolicy) {
24477            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24478                    overridePolicy);
24479        }
24480
24481        @Override
24482        public String getNameForUid(int uid) {
24483            return PackageManagerService.this.getNameForUid(uid);
24484        }
24485
24486        @Override
24487        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24488                Intent origIntent, String resolvedType, String callingPackage,
24489                Bundle verificationBundle, int userId) {
24490            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24491                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24492                    userId);
24493        }
24494
24495        @Override
24496        public void grantEphemeralAccess(int userId, Intent intent,
24497                int targetAppId, int ephemeralAppId) {
24498            synchronized (mPackages) {
24499                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24500                        targetAppId, ephemeralAppId);
24501            }
24502        }
24503
24504        @Override
24505        public boolean isInstantAppInstallerComponent(ComponentName component) {
24506            synchronized (mPackages) {
24507                return mInstantAppInstallerActivity != null
24508                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24509            }
24510        }
24511
24512        @Override
24513        public void pruneInstantApps() {
24514            mInstantAppRegistry.pruneInstantApps();
24515        }
24516
24517        @Override
24518        public String getSetupWizardPackageName() {
24519            return mSetupWizardPackage;
24520        }
24521
24522        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24523            if (policy != null) {
24524                mExternalSourcesPolicy = policy;
24525            }
24526        }
24527
24528        @Override
24529        public boolean isPackagePersistent(String packageName) {
24530            synchronized (mPackages) {
24531                PackageParser.Package pkg = mPackages.get(packageName);
24532                return pkg != null
24533                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24534                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24535                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24536                        : false;
24537            }
24538        }
24539
24540        @Override
24541        public List<PackageInfo> getOverlayPackages(int userId) {
24542            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24543            synchronized (mPackages) {
24544                for (PackageParser.Package p : mPackages.values()) {
24545                    if (p.mOverlayTarget != null) {
24546                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24547                        if (pkg != null) {
24548                            overlayPackages.add(pkg);
24549                        }
24550                    }
24551                }
24552            }
24553            return overlayPackages;
24554        }
24555
24556        @Override
24557        public List<String> getTargetPackageNames(int userId) {
24558            List<String> targetPackages = new ArrayList<>();
24559            synchronized (mPackages) {
24560                for (PackageParser.Package p : mPackages.values()) {
24561                    if (p.mOverlayTarget == null) {
24562                        targetPackages.add(p.packageName);
24563                    }
24564                }
24565            }
24566            return targetPackages;
24567        }
24568
24569        @Override
24570        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24571                @Nullable List<String> overlayPackageNames) {
24572            synchronized (mPackages) {
24573                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24574                    Slog.e(TAG, "failed to find package " + targetPackageName);
24575                    return false;
24576                }
24577
24578                ArrayList<String> paths = null;
24579                if (overlayPackageNames != null) {
24580                    final int N = overlayPackageNames.size();
24581                    paths = new ArrayList<>(N);
24582                    for (int i = 0; i < N; i++) {
24583                        final String packageName = overlayPackageNames.get(i);
24584                        final PackageParser.Package pkg = mPackages.get(packageName);
24585                        if (pkg == null) {
24586                            Slog.e(TAG, "failed to find package " + packageName);
24587                            return false;
24588                        }
24589                        paths.add(pkg.baseCodePath);
24590                    }
24591                }
24592
24593                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
24594                    mEnabledOverlayPaths.get(userId);
24595                if (userSpecificOverlays == null) {
24596                    userSpecificOverlays = new ArrayMap<>();
24597                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
24598                }
24599
24600                if (paths != null && paths.size() > 0) {
24601                    userSpecificOverlays.put(targetPackageName, paths);
24602                } else {
24603                    userSpecificOverlays.remove(targetPackageName);
24604                }
24605                return true;
24606            }
24607        }
24608
24609        @Override
24610        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24611                int flags, int userId) {
24612            return resolveIntentInternal(
24613                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24614        }
24615
24616        @Override
24617        public ResolveInfo resolveService(Intent intent, String resolvedType,
24618                int flags, int userId, int callingUid) {
24619            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24620        }
24621
24622        @Override
24623        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24624            synchronized (mPackages) {
24625                mIsolatedOwners.put(isolatedUid, ownerUid);
24626            }
24627        }
24628
24629        @Override
24630        public void removeIsolatedUid(int isolatedUid) {
24631            synchronized (mPackages) {
24632                mIsolatedOwners.delete(isolatedUid);
24633            }
24634        }
24635
24636        @Override
24637        public int getUidTargetSdkVersion(int uid) {
24638            synchronized (mPackages) {
24639                return getUidTargetSdkVersionLockedLPr(uid);
24640            }
24641        }
24642
24643        @Override
24644        public boolean canAccessInstantApps(int callingUid, int userId) {
24645            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24646        }
24647    }
24648
24649    @Override
24650    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24651        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24652        synchronized (mPackages) {
24653            final long identity = Binder.clearCallingIdentity();
24654            try {
24655                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24656                        packageNames, userId);
24657            } finally {
24658                Binder.restoreCallingIdentity(identity);
24659            }
24660        }
24661    }
24662
24663    @Override
24664    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24665        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24666        synchronized (mPackages) {
24667            final long identity = Binder.clearCallingIdentity();
24668            try {
24669                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24670                        packageNames, userId);
24671            } finally {
24672                Binder.restoreCallingIdentity(identity);
24673            }
24674        }
24675    }
24676
24677    private static void enforceSystemOrPhoneCaller(String tag) {
24678        int callingUid = Binder.getCallingUid();
24679        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24680            throw new SecurityException(
24681                    "Cannot call " + tag + " from UID " + callingUid);
24682        }
24683    }
24684
24685    boolean isHistoricalPackageUsageAvailable() {
24686        return mPackageUsage.isHistoricalPackageUsageAvailable();
24687    }
24688
24689    /**
24690     * Return a <b>copy</b> of the collection of packages known to the package manager.
24691     * @return A copy of the values of mPackages.
24692     */
24693    Collection<PackageParser.Package> getPackages() {
24694        synchronized (mPackages) {
24695            return new ArrayList<>(mPackages.values());
24696        }
24697    }
24698
24699    /**
24700     * Logs process start information (including base APK hash) to the security log.
24701     * @hide
24702     */
24703    @Override
24704    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24705            String apkFile, int pid) {
24706        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24707            return;
24708        }
24709        if (!SecurityLog.isLoggingEnabled()) {
24710            return;
24711        }
24712        Bundle data = new Bundle();
24713        data.putLong("startTimestamp", System.currentTimeMillis());
24714        data.putString("processName", processName);
24715        data.putInt("uid", uid);
24716        data.putString("seinfo", seinfo);
24717        data.putString("apkFile", apkFile);
24718        data.putInt("pid", pid);
24719        Message msg = mProcessLoggingHandler.obtainMessage(
24720                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24721        msg.setData(data);
24722        mProcessLoggingHandler.sendMessage(msg);
24723    }
24724
24725    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24726        return mCompilerStats.getPackageStats(pkgName);
24727    }
24728
24729    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24730        return getOrCreateCompilerPackageStats(pkg.packageName);
24731    }
24732
24733    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24734        return mCompilerStats.getOrCreatePackageStats(pkgName);
24735    }
24736
24737    public void deleteCompilerPackageStats(String pkgName) {
24738        mCompilerStats.deletePackageStats(pkgName);
24739    }
24740
24741    @Override
24742    public int getInstallReason(String packageName, int userId) {
24743        final int callingUid = Binder.getCallingUid();
24744        enforceCrossUserPermission(callingUid, userId,
24745                true /* requireFullPermission */, false /* checkShell */,
24746                "get install reason");
24747        synchronized (mPackages) {
24748            final PackageSetting ps = mSettings.mPackages.get(packageName);
24749            if (filterAppAccessLPr(ps, callingUid, userId)) {
24750                return PackageManager.INSTALL_REASON_UNKNOWN;
24751            }
24752            if (ps != null) {
24753                return ps.getInstallReason(userId);
24754            }
24755        }
24756        return PackageManager.INSTALL_REASON_UNKNOWN;
24757    }
24758
24759    @Override
24760    public boolean canRequestPackageInstalls(String packageName, int userId) {
24761        return canRequestPackageInstallsInternal(packageName, 0, userId,
24762                true /* throwIfPermNotDeclared*/);
24763    }
24764
24765    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24766            boolean throwIfPermNotDeclared) {
24767        int callingUid = Binder.getCallingUid();
24768        int uid = getPackageUid(packageName, 0, userId);
24769        if (callingUid != uid && callingUid != Process.ROOT_UID
24770                && callingUid != Process.SYSTEM_UID) {
24771            throw new SecurityException(
24772                    "Caller uid " + callingUid + " does not own package " + packageName);
24773        }
24774        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24775        if (info == null) {
24776            return false;
24777        }
24778        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24779            return false;
24780        }
24781        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24782        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24783        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24784            if (throwIfPermNotDeclared) {
24785                throw new SecurityException("Need to declare " + appOpPermission
24786                        + " to call this api");
24787            } else {
24788                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24789                return false;
24790            }
24791        }
24792        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24793            return false;
24794        }
24795        if (mExternalSourcesPolicy != null) {
24796            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24797            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24798                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24799            }
24800        }
24801        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24802    }
24803
24804    @Override
24805    public ComponentName getInstantAppResolverSettingsComponent() {
24806        return mInstantAppResolverSettingsComponent;
24807    }
24808
24809    @Override
24810    public ComponentName getInstantAppInstallerComponent() {
24811        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24812            return null;
24813        }
24814        return mInstantAppInstallerActivity == null
24815                ? null : mInstantAppInstallerActivity.getComponentName();
24816    }
24817
24818    @Override
24819    public String getInstantAppAndroidId(String packageName, int userId) {
24820        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24821                "getInstantAppAndroidId");
24822        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24823                true /* requireFullPermission */, false /* checkShell */,
24824                "getInstantAppAndroidId");
24825        // Make sure the target is an Instant App.
24826        if (!isInstantApp(packageName, userId)) {
24827            return null;
24828        }
24829        synchronized (mPackages) {
24830            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24831        }
24832    }
24833}
24834
24835interface PackageSender {
24836    void sendPackageBroadcast(final String action, final String pkg,
24837        final Bundle extras, final int flags, final String targetPkg,
24838        final IIntentReceiver finishedReceiver, final int[] userIds);
24839    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24840        int appId, int... userIds);
24841}
24842